如何在FragmentKotlin中观察Activity Live数据类

0yg35tkg  于 2023-08-07  发布在  Kotlin
关注(0)|答案(2)|浏览(116)

我一直试图观察这段代码的片段,但我没有得到它。如果我在正常活动上使用它,它可以工作,但在片段上它会带来错误。

class HomeFragment : Fragment() {
private lateinit var checkNetworkConnection: CheckNetworkConnection
private lateinit var internetLayout: RelativeLayout
private lateinit var noInternetLayout: RelativeLayout
private lateinit var tryAgainButton: Button
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)

}

override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_home, container, false)

}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    internetLayout = view.findViewById(R.id.internetLayout)
    noInternetLayout = view.findViewById(R.id.noInternetLayout)
    tryAgainButton = view.findViewById(R.id.try_again_button)
    tryAgainButton.setOnClickListener {
        callNetworkConnection()
    }
    callNetworkConnection()
    val url = ""
    val web = view.findViewById<View>(R.id.webView) as WebView
    web.settings.javaScriptEnabled = true
    web.settings.loadWithOverviewMode = true
    web.settings.useWideViewPort = true
    web.settings.builtInZoomControls = true
    web.settings.pluginState = WebSettings.PluginState.ON
    web.webViewClient = WebViewClient()
    web.loadUrl(url)
}

private fun callNetworkConnection() {
    checkNetworkConnection = CheckNetworkConnection()
    checkNetworkConnection.observe(this,{ isConnected ->
        if (isConnected){
            internetLayout.visibility = View.VISIBLE
            noInternetLayout.visibility = View.GONE
        } else {
            noInternetLayout.visibility = View.VISIBLE
            internetLayout.visibility = View.GONE
        }
    })

}

字符串
}
这是我得到的错误:
不能使用提供的参数调用以下函数:公共构造函数CheckNetworkConnection(应用程序:CheckNetworkConnection公共构造函数CheckNetworkConnection(connectivityManager:ConnectivityManager)在com.oreal.ng.CheckNetworkConnection中定义
请帮帮我

d8tt03nd

d8tt03nd1#

给予viewLifecycleOwner而不是this

0s7z1bwu

0s7z1bwu2#

尝试使用requireContext()代替this

相关问题