Android Kotlin Fragments:''试图在空对象参考上调用虚拟方法'''

发布于 2025-02-14 00:34:55 字数 505 浏览 0 评论 0原文

我的主要代码:

    val buttonbckbrowse = findViewById<Button>(R.id.buttonbck)
    buttonbckbrowse.setOnClickListener {
        val webView = findViewById<WebView>(R.id.webViewBrowse)
        webView.goBack()
        Toast.makeText(baseContext, "Back", Toast.LENGTH_SHORT).show()
    }

ButtonBCK处于不同的片段。

尝试运行我的应用程序时,我会得到“''例外:尝试调用虚拟方法'void android.widget.button.setOnclickListener(android.view.view.view $ onclicklistener)'null对象引用)多于。

我不知道我在做什么错。

My code in MainActivity:

    val buttonbckbrowse = findViewById<Button>(R.id.buttonbck)
    buttonbckbrowse.setOnClickListener {
        val webView = findViewById<WebView>(R.id.webViewBrowse)
        webView.goBack()
        Toast.makeText(baseContext, "Back", Toast.LENGTH_SHORT).show()
    }

buttonbck is in a different fragment.

When trying to run my app I get ''Exception: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference'' on the second line in the code above.

I can't figure out what I'm doing wrong.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

何必那么矫情 2025-02-21 00:34:55

直接访问片段视图的活动总是会引起并发症。我建议您重新思考您。

包含按钮的片段应设置单击侦听器。单击按钮时,片段将事件提高到与托管活动共享的对象。 (类似WebViewNavigation)然后,托管活动可以在提高事件时触发WebViewNavigation上的单击“侦听器”,或者WebViewNavigation可以在事件作为流(使用Livesata)发生时宣布,并且该活动可以观察到该活动的流。事件。

Having an activity directly accessing a view of a fragment will always cause complications. I suggest you rethink you approach.

The fragment containing the button should set the click listener. When the button is clicked the fragment raises the event to an object shared with the hosting activity. (Something like WebViewNavigation) The hosting activity can then just set a click listener on WebViewNavigation to be triggered when the event is raised, or the WebViewNavigation can announce when an event occurs as a stream (using LiveData) and the activity can observe that stream of events.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文