dwv*_*ldg 5 java android nullpointerexception kotlin android-viewbinding
我正在尝试使用 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
}
}
Run Code Online (Sandbox Code Playgroud)
这是例外情况:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
Run Code Online (Sandbox Code Playgroud)
小智 0
因为视图还没有创建。您应该在 onViewCreated() 函数中调用视图。 阅读更多
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
start_button.setOnClickListener(
Navigation.createNavigateOnClickListener(R.id.action_fragmentStart_to_fragmentQuestion,null)
)
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9737 次 |
| 最近记录: |