44

我开始使用 ViewBinding。在搜索了一些示例或建议如何将 ViewBinding 与抽象基类一起使用后,该抽象基类应处理预期出现在每个子布局中的视图的相同逻辑,我最终在此处发布了此问题。

场景:
我有一个基类public abstract class BaseFragment。有多个片段扩展了这个基类。这些片段具有从基类实现处理的公共视图(使用“旧” findViewById())。例如,每个片段的布局都应该包含一个 ID 为 text_title 的 TextView。BaseFragment以下是从's处理它的方式onViewCreated()

TextView title = view.findViewById(R.id.text_title);
// Do something with the view from the base class

现在 ViewBinding-API 为每个子片段生成绑定类。我可以使用绑定来引用视图。但我不能使用基类中的具体绑定。即使在基类中引入了泛型,也有太多类型的片段绑定,我暂时放弃了这个解决方案。

从抽象基类处理绑定视图的推荐方法是什么?有没有最佳实践?没有在 API 中找到一种内置机制来优雅地处理这种情况。

当期望子片段包含公共视图时,我可以提供抽象方法,从片段的具体绑定返回视图,并使它们可以从基类访问。(例如protected abstract TextView getTitleView();)。但这是一个优势而不是使用findViewById()?你怎么看?还有其他(更好的)解决方案吗?请让我们开始一些讨论。

4

9 回答 9

38

嗨,我创建了一篇博客文章,其中深入介绍了视图绑定,还包括组合模式/委托模式来实现视图绑定以及使用链接中的继承检出

结帐以获取完整代码BaseActivity以及BaseFragment使用情况

Androidbites|ViewBinding

/*
 * In Activity
 * source : https://chetangupta.net/viewbinding/
 * Author : ChetanGupta.net
 */
abstract class ViewBindingActivity<VB : ViewBinding> : AppCompatActivity() {

    private var _binding: ViewBinding? = null
    abstract val bindingInflater: (LayoutInflater) -> VB

    @Suppress("UNCHECKED_CAST")
    protected val binding: VB
        get() = _binding as VB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        _binding = bindingInflater.invoke(layoutInflater)
        setContentView(requireNotNull(_binding).root)
        setup()
    }

    abstract fun setup()

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}
/*
 * In Fragment
 * source : https://chetangupta.net/viewbinding/
 * Author : ChetanGupta.net
 */
abstract class ViewBindingFragment<VB : ViewBinding> : Fragment() {

    private var _binding: ViewBinding? = null
    abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB

    @Suppress("UNCHECKED_CAST")
    protected val binding: VB
        get() = _binding as VB

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        _binding = bindingInflater.invoke(inflater, container, false)
        return requireNotNull(_binding).root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setup()
    }

    abstract fun setup()

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

关于使用、高级模式和反模式检查博客Androidbites|ViewBinding

于 2020-12-06T10:03:01.437 回答
9

我找到了适用于我的具体场景的解决方案,我不想与你分享。

请注意,这不是对如何ViewBinding工作的解释。

我在下面创建了一些伪代码与您分享。DialogFragments(使用该显示从我的解决方案迁移AlertDialog)。我希望它几乎正确地适应了 Fragments ( onCreateView()vs. onCreateDialog())。我让它以这种方式工作。

想象一下,我们有一个抽象BaseFragment类和两个扩展类FragmentA,并且FragmentB.

首先看看我们所有的布局。请注意,我将布局的可重用部分移出到一个单独的文件中,稍后将包含在具体片段的布局中。特定视图保留在其片段的布局中。对于这种情况,使用常用布局很重要。

片段_a.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
    <!-- FragmentA-specific views -->
    <EditText
        android:id="@+id/edit_name"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:inputType="text" />
    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/edit_name">

        <!-- Include the common layout -->
        <include
            layout="@layout/common_layout.xml"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>
</RelativeLayout>

片段_b.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">
    
    <!-- FragmentB-specific, differs from FragmentA -->
    <TextView
        android:id="@+id/text_explain"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="@string/explain" />
    
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_explain">

        <!-- Include the common layout -->
        <include
            layout="@layout/common_layout.xml"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </RelativeLayout>
</RelativeLayout>

common_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:parentTag="android.widget.RelativeLayout">

    <Button
        android:id="@+id/button_up"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/up"/>

    <Button
        android:id="@+id/button_down"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/button_up"
        android:text="@string/down" />
</merge>

接下来是片段类。首先是我们的BaseFragment实现。

onCreateView()是绑定膨胀的地方。我们能够CommonLayoutBinding根据包含 的片段的绑定来绑定common_layout.xmlonCreateViewBinding()我定义了一个在其之上调用的抽象方法,onCreateView()它返回VewBindingfromFragmentAFragmentB. 这样,当我需要创建CommonLayoutBinding.

接下来我可以CommonLayoutBinding通过调用来创建一个实例commonBinding = CommonLayoutBinding.bind(binding.getRoot());。请注意,来自具体片段绑定的根视图被传递给bind().

getCommonBinding()允许提供CommonLayoutBinding对扩展片段的访问。我们可以更严格:BaseFragment应该提供访问该绑定的具体方法,而不是将其公开给它的子类。

private CommonLayoutBinding commonBinding; // common_layout.xml

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 
        @Nullable Bundle savedInstanceState) {
    // Make sure to create the concrete binding while it's required to 
    // create the commonBinding from it
    ViewBinding binding = onCreateViewBinding(inflater);
    // We're using the concrete layout of the child class to create our 
    // commonly used binding 
    commonBinding = CommonLayoutBinding.bind(binding.getRoot());
    // ...
    return binding.getRoot();
}

// Makes shure to create the concrete binding class from child-classes before 
// the commonBinding can be bound
@NonNull
protected abstract ViewBinding onCreateViewBinding(@NonNull LayoutInflater inflater, 
        @Nullable ViewGroup container);

// Allows child-classes to access the commonBinding to access common 
// used views
protected CommonLayoutBinding getCommonBinding() {
    return commonBinding;
}

现在看看其中一个子类,FragmentA. 从onCreateViewBinding()我们创建我们的绑定,就像我们从onCreateView(). 在原则上,它仍然被称为 from onCreateVIew()。如上所述,此绑定从基类中使用。我正在使用getCommonBinding()能够从common_layout.xml. 现在,每个子类BaseFragment都可以从ViewBinding.

这样我就可以将所有基于通用视图的逻辑上移到基类。

private FragmentABinding binding; // fragment_a.xml

@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, 
        @Nullable Bundle savedInstanceState) {
    // Make sure commonBinding is present before calling super.onCreateView() 
    // (onCreateViewBinding() needs to deliver a result!)
    View view = super.onCreateView(inflater, container, savedInstanceState);
    binding.editName.setText("Test");
    // ...
    CommonLayoutBinding commonBinding = getCommonBinding();
    commonBinding.buttonUp.setOnClickListener(v -> {
        // Handle onClick-event...
    });
    // ...
    return view;
}

// This comes from the base class and makes sure we have the required 
// binding-instance, see BaseFragment
@Override
protected ViewBinding onCreateViewBinding(@NonNull LayoutInflater inflater, 
        @Nullable ViewGroup container) {
    binding = FragmentABinding.inflate(inflater, container, false);
    return binding;
}

优点:

  • 通过将其移动到基类来减少重复代码。所有片段中的代码现在更加清晰,并简化为它们的本质
  • 通过将可重用视图移动到通过<include />

缺点:

  • 可能不完全适用于无法将视图移动到常用布局文件中的情况
    • 可能视图需要在片段/布局之间定位不同
    • 许多<included />布局会导致许多 Binding 类,然后没有什么可取胜的
  • 需要另一个绑定实例 ( CommonLayoutBinding)。FragmentA每个子 ( , )不仅有一个绑定类,FragmentB它提供对视图层次结构中所有视图的访问

如果视图不能移动到通用布局中怎么办?
我对如何将其作为最佳实践来解决非常感兴趣!让我们考虑一下:在具体的ViewBinding. 我们可以引入一个接口来提供对常用视图的访问。从片段中,我们将绑定包装在这些包装类中。另一方面,这将导致每个 ViewBinding 类型的许多包装器。但是我们可以将这些包装器提供给BaseFragment使用抽象方法(泛型)。BaseFragment然后能够使用定义的接口方法访问视图或处理它们。你怎么看?

总之:
也许它只是 ViewBinding 的实际限制,一个布局需要有它自己的 Binding 类。如果您在无法共享布局并且需要在每个布局中声明重复的情况下找到了一个好的解决方案,请告诉我。

我不知道这是否是最佳实践,或者是否有更好的解决方案。但是,直到这是我用例的唯一已知解决方案,这似乎是一个好的开始!

于 2020-11-13T10:47:20.593 回答
6

这是我的完整示例BaseViewBindingFragment

  • 不需要任何abstract属性或功能,
  • 它依赖于Java 反射(不是 Kotlin 反射) - 请参阅使用泛型类型参数的fun createBindingInstance地方VB
package app.fragment

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.viewbinding.ViewBinding
import java.lang.reflect.ParameterizedType

/**
 * Base application `Fragment` class with overridden [onCreateView] that inflates the view
 * based on the [VB] type argument and set the [binding] property.
 *
 * @param VB The type of the View Binding class.
 */
open class BaseViewBindingFragment<VB : ViewBinding> : Fragment() {

    /** The view binding instance. */
    protected var binding: VB? = null

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View =
        createBindingInstance(inflater, container).also { binding = it }.root

    override fun onDestroyView() {
        super.onDestroyView()

        binding = null
    }

    /** Creates new [VB] instance using reflection. */
    @Suppress("UNCHECKED_CAST")
    protected open fun createBindingInstance(inflater: LayoutInflater, container: ViewGroup?): VB {
        val vbType = (javaClass.genericSuperclass as ParameterizedType).actualTypeArguments[0]
        val vbClass = vbType as Class<VB>
        val method = vbClass.getMethod("inflate", LayoutInflater::class.java, ViewGroup::class.java, Boolean::class.java)

        // Call VB.inflate(inflater, container, false) Java static method
        return method.invoke(null, inflater, container, false) as VB
    }
}
于 2021-05-05T05:47:01.100 回答
3

基类会这样

abstract class BaseActivity<VB : ViewBinding> : AppCompatActivity(){

    protected lateinit var binding : VB

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = inflateLayout(layoutInflater)
        setContentView(binding.root)
    }

    abstract fun inflateLayout(layoutInflater: LayoutInflater) : VB
}

现在在您要使用的活动中

class MainActivity : BaseActivity<ActivityMainBinding>(){

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding.tvName.text="ankit"
    }

    override fun inflateLayout(layoutInflater: LayoutInflater)  = ActivityMainBinding.inflate(layoutInflater)
}

现在在 onCreate 中只需根据使用情况使用绑定

于 2021-07-11T17:52:49.947 回答
3

我创建了这个抽象类作为基础;

abstract class BaseFragment<VB : ViewBinding> : Fragment() {

private var _binding: VB? = null

val binding get() = _binding!!

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

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

abstract fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?): VB

}

用法;

class HomeFragment : BaseFragment<FragmentHomeBinding>() {

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    
    binding.textViewTitle.text = ""
}

override fun inflateViewBinding(inflater: LayoutInflater, container: ViewGroup?): FragmentHomeBinding {
    return FragmentHomeBinding.inflate(inflater, container, false)
}

}

于 2021-07-23T12:04:35.750 回答
1

2021 年 2 月 4 日更新:在研究并从许多来源获得灵感后,我写了一篇文章。这篇文章将根据我未来在视图绑定方面的经验进行更新,因为我们公司现在已经放弃了近 80% 的合成绑定。


我还提出了一个有效使用最终变量的基类解决方案。我的主要目标是:

  1. 处理基类中的所有绑定生命周期
  2. 让子类提供绑定类实例而不单独使用该路由(例如,如果我有一个抽象函数abstract fun getBind():T,子类可以实现它并直接调用它。我不希望这样,因为这会使我相信在基类中保持绑定没有实际意义)

所以就在这里。首先是我的应用程序的当前结构。活动不会自行膨胀,基类会为它们做:

儿童活动和片段:

class MainActivity : BaseActivityCurrent(){

    var i = 0

    override val contentView: Int
        get() = R.layout.main_activity


    override fun setup() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, MainFragment())
            .commitNow()

        syntheticApproachActivity()
    }


    private fun syntheticApproachActivity() {
        btText?.setOnClickListener { tvText?.text = "The current click count is ${++i}"  }
    }


    private fun fidApproachActivity() {
        val bt = findViewById<Button>(R.id.btText)
        val tv = findViewById<TextView>(R.id.tvText)

        bt.setOnClickListener { tv.text = "The current click count is ${++i}"  }
    }
}

//-----------------------------------------------------------
class MainFragment : BaseFragmentCurrent() {
    override val contentView: Int
        get() = R.layout.main_fragment


    override fun setup() {
        syntheticsApproach()
    }

    private fun syntheticsApproach() {
        rbGroup?.setOnCheckedChangeListener{ _, id ->
            when(id){
                radioBt1?.id -> tvFragOutPut?.text = "You Opt in for additional content"
                radioBt2?.id -> tvFragOutPut?.text = "You DO NOT Opt in for additional content"
            }
        }

    }

    private fun fidApproach(view: View) {
        val rg: RadioGroup? = view.findViewById(R.id.rbGroup)
        val rb1: RadioButton? = view.findViewById(R.id.radioBt1)
        val rb2: RadioButton? = view.findViewById(R.id.radioBt2)
        val tvOut: TextView? = view.findViewById(R.id.tvFragOutPut)
        val cbDisable: CheckBox? = view.findViewById(R.id.cbox)

        rg?.setOnCheckedChangeListener { _, checkedId ->
            when (checkedId) {
                rb1?.id -> tvOut?.text = "You Opt in for additional content"
                rb2?.id -> tvOut?.text = "You DO NOT Opt in for additional content"
            }
        }

        rb1?.isChecked = true
        rb2?.isChecked = false

        cbDisable?.setOnCheckedChangeListener { _, bool ->
            rb1?.isEnabled = bool
            rb2?.isEnabled = bool
        }


    }


}

基础活动和片段:


abstract class BaseActivityCurrent :AppCompatActivity(){

    abstract val contentView: Int


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(contentView)
        setup()
    }

    abstract fun setup()

}
abstract class BaseFragmentCurrent : Fragment(){


    abstract val contentView: Int

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return inflater.inflate(contentView,container,false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        setup()
    }

    abstract fun setup()


}

正如您所看到的,儿童班总是很容易扩展,因为基础活动会完成所有繁重的工作。并且由于合成材料被广泛使用,因此没有太大问题。要使用具有前面提到的约束的绑定类,我会:

  1. 需要子类实现将数据提供回父片段的功能。这很容易,只需创建更多返回子绑定类实例的抽象函数即可。

  2. 将子类的视图绑定存储在一个变量(比如val binding:T)中,以便基类可以在销毁广告时将其取消,并相应地处理生命周期。有点棘手,因为事先不知道孩子的 Binding 类实例类型。但是将父级设为通用(<T:ViewBinding>)将完成这项工作

  3. 将视图返回给系统进行通货膨胀。再次,很容易,因为谢天谢地,对于大多数组件,系统接受一个膨胀的视图,并且拥有孩子的绑定实例将让我向系统提供一个视图

  4. 防止子类直接使用第 1 点创建的路由。想一想:如果一个子类有一个getBind(){...}返回他们自己的绑定类实例的函数,他们为什么不使用它而使用super.binding? 是什么阻止他们使用getBind()onDestroy() 中的函数,而不应该访问绑定?

所以这就是为什么我将该函数设为 void 并将一个可变列表传递给它。子类现在会将它们的绑定添加到父类将访问的列表中。如果他们不这样做,它会抛出一个 NPE 。如果他们试图在销毁或其他地方使用它,它会再次抛出一个illegalstate exception. 我还创建了一个方便的高阶函数withBinding(..) 以方便使用。

基础绑定活动和片段:



abstract class BaseActivityFinal<VB_CHILD : ViewBinding> : AppCompatActivity() {

    private var binding: VB_CHILD? = null


    //lifecycle
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getInflatedLayout(layoutInflater))
        setup()
    }
    override fun onDestroy() {
        super.onDestroy()
        this.binding = null
    }


    //internal functions
    private fun getInflatedLayout(inflater: LayoutInflater): View {
        val tempList = mutableListOf<VB_CHILD>()
        attachBinding(tempList, inflater)
        this.binding = tempList[0]


        return binding?.root?: error("Please add your inflated binding class instance at 0th position in list")
    }

    //abstract functions
    abstract fun attachBinding(list: MutableList<VB_CHILD>, layoutInflater: LayoutInflater)

    abstract fun setup()

    //helpers
    fun withBinding(block: (VB_CHILD.() -> Unit)?): VB_CHILD {
        val bindingAfterRunning:VB_CHILD? = binding?.apply { block?.invoke(this) }
        return bindingAfterRunning
            ?:  error("Accessing binding outside of lifecycle: ${this::class.java.simpleName}")
    }


}

//--------------------------------------------------------------------------

abstract class BaseFragmentFinal<VB_CHILD : ViewBinding> : Fragment() {

    private var binding: VB_CHILD? = null


    //lifecycle
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ) = getInflatedView(inflater, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setup()
    }

    override fun onDestroy() {
        super.onDestroy()
        this.binding = null
    }


    //internal functions
    private fun getInflatedView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        attachToRoot: Boolean
    ): View {
        val tempList = mutableListOf<VB_CHILD>()
        attachBinding(tempList, inflater, container, attachToRoot)
        this.binding = tempList[0]
        return binding?.root
            ?: error("Please add your inflated binding class instance at 0th position in list")

    }

    //abstract functions
    abstract fun attachBinding(
        list: MutableList<VB_CHILD>,
        layoutInflater: LayoutInflater,
        container: ViewGroup?,
        attachToRoot: Boolean
    )

    abstract fun setup()

    //helpers
    fun withBinding(block: (VB_CHILD.() -> Unit)?): VB_CHILD {
        val bindingAfterRunning:VB_CHILD? = binding?.apply { block?.invoke(this) }
        return bindingAfterRunning
            ?:  error("Accessing binding outside of lifecycle: ${this::class.java.simpleName}")
    }

}

子活动和片段:


class MainActivityFinal:BaseActivityFinal<MainActivityBinding>() {
    var i = 0

    override fun setup() {
        supportFragmentManager.beginTransaction()
            .replace(R.id.container, MainFragmentFinal())
            .commitNow()

        viewBindingApproach()
    }
    
    private fun viewBindingApproach() {
        withBinding {
            btText.setOnClickListener { tvText.text = "The current click count is ${++i}"  }
            btText.performClick()
        }

    }
    
    override fun attachBinding(list: MutableList<MainActivityBinding>, layoutInflater: LayoutInflater) {
        list.add(MainActivityBinding.inflate(layoutInflater))
    }
}

//-------------------------------------------------------------------

class MainFragmentFinal : BaseFragmentFinal<MainFragmentBinding>() {
   
    override fun setup() {
        bindingApproach()
    }

    private fun bindingApproach() {
        withBinding {
            rbGroup.setOnCheckedChangeListener{ _, id ->
                when(id){
                    radioBt1.id -> tvFragOutPut.text = "You Opt in for additional content"
                    radioBt2.id -> tvFragOutPut.text = "You DO NOT Opt in for additional content"
                }
            }
            radioBt1.isChecked = true
            radioBt2.isChecked = false

            cbox.setOnCheckedChangeListener { _, bool ->
                radioBt1.isEnabled = !bool
                radioBt2.isEnabled = !bool
            }
        }
    }


    override fun attachBinding(
        list: MutableList<MainFragmentBinding>,
        layoutInflater: LayoutInflater,
        container: ViewGroup?,
        attachToRoot: Boolean
    ) {
        list.add(MainFragmentBinding.inflate(layoutInflater,container,attachToRoot))
    }


}


于 2020-11-17T16:33:56.533 回答
0
inline fun <reified BindingT : ViewBinding> AppCompatActivity.viewBindings(
    crossinline bind: (View) -> BindingT
) = object : Lazy<BindingT> {

    private var initialized: BindingT? = null

    override val value: BindingT
        get() = initialized ?: bind(
            findViewById<ViewGroup>(android.R.id.content).getChildAt(0)
        ).also {
            initialized = it
        }

    override fun isInitialized() = initialized != null
}

于 2021-05-04T08:28:49.610 回答
0

我认为一个简单的反应是使用bind公共类的方法。

我知道这不适用于所有情况,但它适用于具有相似元素的视图。

如果我有两个布局row_type_1.xml并且row_type_2.xml它们共享共同的元素,那么我可以执行以下操作:

ROW_TYPE_1 -> CommonRowViewHolder(
                    RowType1Binding.inflate(LayoutInflater.from(parent.context), parent, false))

然后对于类型 2,不要创建另一个 ViewHolder 来接收它自己的 Binding 类,而是执行以下操作:

ROW_TYPE_2 -> {
    val type2Binding = RowType2Binding.inflate(LayoutInflater.from(parent.context), parent, false))
    CommonRowViewHolder(RowType1Binding.bind(type2Binding))
}

如果它是组件的子集,则可以放置继承

CommonRowViewHolder: ViewHolder {
    fun bind(binding: RowType1Holder)
}

Type2RowViewHolder: CommonRowViewHolder {

    fun bind(binding: RowType2Holder) {
        super.bind(Type1RowViewHolder.bind(binding))
        
        //perform specific views for type 2 binding ...
    }
}
于 2021-05-03T19:01:09.180 回答
-1

这是对伟大的Chetan Gupta 的回答稍作修改的 Kotlin 版本。避免使用“UNCHECKED_CAST”。

活动

abstract class BaseViewBindingActivity<ViewBindingType : ViewBinding> : AppCompatActivity() {

    protected lateinit var binding: ViewBindingType
    protected abstract val bindingInflater: (LayoutInflater) -> ViewBindingType

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = bindingInflater.invoke(layoutInflater)
        val view = binding.root
        setContentView(view)
    }
}

分段

abstract class BaseViewBindingFragment<ViewBindingType : ViewBinding> : Fragment() {

    private var _binding: ViewBindingType? = null
    protected val binding get() = requireNotNull(_binding)
    protected abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> ViewBindingType

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

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}
于 2021-01-26T13:08:43.900 回答