我正在尝试使用 kotlin View 绑定(bind)向 fragment 内的按钮添加单击监听器。我在 onCreateView 方法中设置点击监听器。当我这样做时,我得到一个空指针异常,因为按钮尚未创建。我认为 kotlin View 绑定(bind)负责 View 初始化,因此按钮不应该为空?
这是我的代码:
class FragmentStart : Fragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val view = inflater.inflate(R.layout.fragment_start, container, false)
start_button.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_fragmentStart_to_fragmentQuestion,null)
)
return view
}
}
这是一个异常(exception):
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
最佳答案
因为 View 还没有创建。您应该在 onViewCreated() 函数中调用 View 。 read more
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
start_button.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_fragmentStart_to_fragmentQuestion,null)
)
}
关于java - 在 Fragment 中使用 Kotlin ViewBinding 时出现 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58248031/