You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android中如何通过DataBindingUtil绑定content.xml内include引入的fragment_list布局

解决方法

第一步:改造布局文件

两个布局都需要用<layout>标签作为根节点,开启DataBinding支持。

修改后的content.xml:

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        
        <view.TouchyWebView
            android:id="@+id/content_view"
            android:layout_width="match_parent"
            android:layout_height="100dp" />

        <include
            android:id="@+id/view_list"
            layout="@layout/fragment_list"
            android:layout_width="match_parent"
            android:layout_height="596dp"
            app:layout_constraintTop_toBottomOf="@+id/content_view"
            tools:layout_editor_absoluteX="-9dp" />
    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

确保fragment_list.xml也用作为根节点,示例:

<layout xmlns:android="http://schemas.android.com/apk/res/android">
    <!-- 原有fragment_list布局内容 -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
        ...
    </LinearLayout>
</layout>

第二步:绑定代码实现

方式1:直接用DataBindingUtil加载content布局

// 加载content布局生成父布局绑定类
ContentBinding contentBinding = DataBindingUtil.inflate(inflater, R.layout.content, container, false);
// 直接获取WebView实例
WebView webView = contentBinding.contentView;
// 获取include引入的fragment_list布局的绑定实例
FragmentListBinding fragmentListBinding = contentBinding.viewList;

// 若需要返回根视图,调用contentBinding.getRoot()即可

方式2:如果已经提前inflate了content的View,用bind方法绑定

View view = inflater.inflate(R.layout.content, container, false);
// 绑定已经inflate的View
ContentBinding contentBinding = DataBindingUtil.bind(view);
WebView webView = contentBinding.contentView;
FragmentListBinding fragmentListBinding = contentBinding.viewList;

注意事项

  • include标签必须设置独立id,才能在父布局绑定类中生成对应子布局绑定的字段,字段名为id的驼峰形式,示例中view_list对应字段为viewList
  • 两个布局都必须套<layout>根标签,否则不会生成对应绑定类,无法正常获取子布局绑定实例

内容的提问来源于stack exchange,提问作者Slava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 14:36:02