生成的片段绑定不包含我的自定义视图 ID

Generated FragmentBinding does not contain my CustomView id

我在我的 android 项目中使用数据绑定,我的 dashboard_fragment_layout.xml 包含包含 TextView 和 CustomView 的 LinearLayout:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.ui.dashboard.DashboardFragment">
    <data>
        <variable
            name="ViewModel"
            type="com.example.ui.dashboard.DashboardViewModel" />
    </data>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/tvSome"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        <view
            android:id="@+id/viewCustom"
            class="com.example.ui.dashboard.CustomView"
            android:layout_width="300dp"
            android:layout_height="match_parent"
            android:layout_gravity="bottom|center_horizontal" />
    </LinearLayout>
</layout>

当我尝试通过生成的 FragmentDashboardBinding 访问我的自定义视图时:

mCustomView = mBinding.viewCustom;

我在 AndroidStudio 中收到“无法解析符号 viewCustom”。我对 TextView 没有这个问题,它可以从 mBinding 对象访问:

mSomeTextView = mBinding.tvSome;  // all fine, no errors

我总是在使用自定义视图时遇到此错误,访问我的自定义视图对象的唯一方法是使用 findViewById 以旧方式执行此操作:

mCustomView = view.findViewById(R.id.viewCustom); // that works

总计:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mViewDataBinding = DataBindingUtil.inflate(inflater, fragment_dashboard_layout, container, false);
        view = mViewDataBinding.getRoot();

        mCustomView = mViewDataBinding.viewCustom;   // 'Can't resolve symbol viewCustom
        mTextView = mViewDataBinding.tvSome;  // all fine
        mCustomView = view.findViewById(R.id.viewCustom);  // that works
    }

如何通过生成的数据绑定对象访问自定义视图?

您使用了错误的视图标签。尝试将 view 标签替换为 View 将您的视图代码替换为此。

<View
        android:id="@+id/viewCustom"
        class="com.example.ui.dashboard.CustomView"
        android:layout_width="300dp"
        android:layout_height="match_parent"
        android:layout_gravity="bottom|center_horizontal" />

编码愉快!!

在 xml 代码中更改为 com.example.ui.dashboard.CustomView

并删除 xml 代码中的 class 。

试试这个。

<com.example.ui.dashboard.CustomView
    android:id="@+id/viewCustom"
    android:layout_width="300dp"
    android:layout_height="match_parent"
    android:layout_gravity="bottom|center_horizontal" />