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

如何在含公共引入布局的抽象Fragment中使用Jetpack View Binding

抽象Fragment使用View Binding的实现方案

核心逻辑:你引入的公共布局会自动生成对应的Binding类,只需要在子布局的<include>标签加统一ID,子Fragment的Binding会自动生成公共布局的Binding实例,抽象类声明抽象属性获取该实例即可。

步骤1:修改子布局的<include>标签添加ID

给两个子Fragment布局里的公共布局引入标签统一加ID(如commonLayout),以fragment_a_example.xml为例:

<include
    android:id="@+id/commonLayout"
    layout="@layout/fragment_example_abstract"
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

fragment_b_example.xml里的<include>标签也添加相同的android:id="@+id/commonLayout"属性。

步骤2:修改抽象Fragment声明公共Binding属性

abstract class ExampleAbstractFragment : Fragment() {
    // 声明抽象属性,由子类返回公共布局的Binding实例
    protected abstract val commonBinding: FragmentExampleAbstractBinding

    override fun doSomething() {
        // 直接通过公共Binding获取控件,无需findViewById
        val abstractTextView = commonBinding.abstractTextView
        val abstractButton = commonBinding.abstractButton
        // 原有公共逻辑保持不变
    }
}

步骤3:修改子Fragment实现抽象属性

以ExampleFragmentA.kt为例:

class ExampleFragmentA : ExampleAbstractFragment() {
    private var _binding: FragmentAExampleBinding? = null
    private val binding get() = _binding!!
    
    // 实现父类抽象属性,返回当前Binding中的公共布局实例
    override val commonBinding: FragmentExampleAbstractBinding
        get() = binding.commonLayout

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        _binding = FragmentAExampleBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onDestroyView() {
        _binding = null
        super.onDestroyView()
    }

    override fun doSomething() {
        super.doSomething() // 调用父类公共逻辑
        val textView = binding.fragmentAExampleTextView
        val button = binding.fragmentAExampleButton
    }
}

ExampleFragmentB.kt按照相同逻辑修改,实现commonBinding属性返回binding.commonLayout即可。

注意事项

  • 所有子Fragment的公共布局<include>标签ID必须保持一致
  • 公共布局的Binding类FragmentExampleAbstractBinding为View Binding自动生成,只要开启View Binding功能就会正常生成
  • commonBinding的生命周期和子Fragment的私有的Binding完全一致,不要在onDestroyView之后访问

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 11:24:04