Android Kotlin Fragments:''试图在空对象参考上调用虚拟方法'''
我的主要代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
直接访问片段视图的活动总是会引起并发症。我建议您重新思考您。
包含按钮的片段应设置单击侦听器。单击按钮时,片段将事件提高到与托管活动共享的对象。 (类似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.