首页 > 解决方案 > 在 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

标签: javaandroidkotlinandroid-viewbinding

解决方案


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)
            )
    }

推荐阅读