java - 在 Fragment 中使用 Kotlin ViewBinding 时出现 NullPointerException

标签 java android kotlin android-viewbinding

我正在尝试使用 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/

相关文章:

java - 更改日期选择器对话框当前日期 - android java

android - 删除 kotlin-android-extensions 插件后 Gradle 不同步

java - 如何以编程方式获得应用程序支持的语言

java - 使用 session 加载图像名称

javascript - css 或 javascript 中的简单飞行文本?

android - 如何避免 Android 测试应用程序中的代码重复?

android - 在 Kotlin 中使用 @Parcelize 注释的 NoSuchMethodError

maven - JRebel 可以在 maven 上的 kotlin-maven-plugin 插件使用时重新加载 Kotlin 类吗?

java - ImageMagick 和 Java Runtime Exec 的问题

java - 在具有设置菜单项的 ActionBar 上禁用弹出按钮