如何解决数据绑定为空
为了启用数据绑定,我在 build.gradle
文件中添加了:
android {
...
buildFeatures {
dataBinding true
}
}
在我的片段中,我添加了:
private var _binding: WebViewFragmentBinding? = null
private val binding get() = _binding!!
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
_binding = WebViewFragmentBinding.inflate(inflater,container,false)
return binding.root
}
到目前为止,这一直有效,直到我从以下位置更改布局:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebViewFragment">
// more layout elements
</FrameLayout>
到:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<data>
<variable
name="name"
type="String" />
</data>
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".WebViewFragment">
// more layout elements
</FrameLayout>
</layout>
当我添加 layout
元素时,_binding
对象是 null
。
我不知道我的代码有什么问题。当我运行应用程序时,它因 NPE 崩溃,但控制台上没有膨胀错误或任何内容。
解决方法
private var _binding: WebViewFragmentBinding? = null
override fun onCreateView(inflater: LayoutInflater,container: ViewGroup?,savedInstanceState: Bundle?): View? {
_binding = WebViewFragmentBinding.inflate(inflater,container,false)
return _binding.root
}
在任何地方使用这个 _binding,比如 _binding.youView
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。