java - 在 Fragment 中使用 Kotlin ViewBinding 时出现 NullPointerException
问题描述
我正在尝试使用 kotlin 视图绑定将点击侦听器添加到我的片段内的按钮。我在 onCreateView 方法中设置点击监听器。当我这样做时,我得到一个空指针异常,因为尚未创建按钮。我认为 kotlin 视图绑定负责视图初始化,所以按钮不应该为空?
这是我的代码:
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
}
}
这是一个例外:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
解决方案
Because the view has not been created yet. You should call the view in the onViewCreated () function. 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)
)
}
推荐阅读
- react-native - 本机基础缩略图不接受图像源
- javascript - 从 javascript 发送 POST 表单时从当前窗口重定向
- authentication - Rally 休息 API 的问题 - .Net
- php - Confusion about object companion after using Laravel factory()->create()
- javascript - RXJS Angular - 如何在包含可观察对象的 foreach 循环结束时调用函数?
- c++ - 使用 Boost HOF 实现 STL 漂亮打印
- java - 计算单个玩家的平均得分
- c# - ef core - 如何将类映射的多个变体映射到同一个表
- javascript - 选择至少一项 li 验证
- c++ - C++ 函数定义中的“Type&”与“Type*”