首页 > 解决方案 > 数据绑定为空

问题描述

为了启用数据绑定,我在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 而崩溃,但控制台上没有任何充气错误或任何东西。

标签: androidandroid-fragmentsandroid-databinding

解决方案


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


推荐阅读