android - 数据绑定为空
问题描述
为了启用数据绑定,我在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.youView 之类的任何地方使用这个 _binding
推荐阅读
- jquery - 无法在视图页面中获取 ajax 响应
- string - 搜索字符串后如何在 Perl 中重复三次
- c# - C# 创建泛型函数列表
- c - 使用 fork (process) 而不是 pthread 来实现相同的
- python-3.x - 如何使用reduce在无序列表中搜索键?
- treeview - Avalonia 动态树视图 MVVM
- ruby-on-rails-6 - 在 AWS 中基于用户名 rails 6.1.1 应用程序登录后路由用户
- typescript - 如何在 Typescript 中使用装饰器更改函数参数类型
- coq - 在 coq 中定义多态归纳类型树
- javascript - 未定义,找不到错误