[英]How using ViewBinding with an abstract base class
我开始使用 ViewBinding。 在搜索了一些示例或建议如何将 ViewBinding 与抽象基础 class 一起使用后,该抽象基础应该处理预期在每个孩子的布局中出现的视图的相同逻辑,我最终在这里发布了这个问题。
设想:
我有一个基础 class public abstract class BaseFragment
。 有多个片段扩展了这个基础 class。 这些片段具有从基本 class 实现处理的公共视图(使用“旧” findViewById()
)。 例如,每个片段的布局都应包含一个 ID 为 text_title 的 TextView。 下面是从BaseFragment
的onViewCreated()
处理它的方式:
TextView title = view.findViewById(R.id.text_title);
// Do something with the view from the base class
现在 ViewBinding-API 为每个子片段生成绑定类。 我可以使用绑定来引用视图。 但我不能使用基础 class 中的具体绑定。 即使将 generics 引入到基础 class 中,仍然有太多类型的片段绑定,我暂时放弃了这个解决方案。
从抽象基础 class 处理绑定视图的推荐方法是什么? 有没有最佳实践? 没有在 API 中找到一种内置机制来优雅地处理这种情况。
当期望子片段包含公共视图时,我可以提供抽象方法,从片段的具体绑定返回视图,并使它们可以从基础 class 访问。 (例如protected abstract TextView getTitleView();
)。 但这是一个优势而不是使用findViewById()
吗? 你怎么看? 还有其他(更好的)解决方案吗? 请让我们开始一些讨论。
嗨,我创建了一篇博客文章,其中深入介绍了视图绑定,还包括组合模式/委托模式以实现视图绑定以及使用 inheritance 从链接结帐
BaseFragment
BaseActivity
完整代码以及用法
/*
* 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
我找到了适用于我的具体场景的解决方案,我不想与你分享。
请注意,这不是对ViewBinding
如何工作的解释。
我在下面创建了一些伪代码与您分享。 (使用显示AlertDialog
DialogFragments
我的解决方案迁移)。 我希望它几乎适用于片段( onCreateView()
与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()
是绑定膨胀的地方。 我们能够基于包含common_layout.xml
CommonLayoutBinding
我定义了一个在 onCreateView() 之上调用的抽象方法onCreateViewBinding()
onCreateView()
,它从FragmentA
和FragmentB
返回VewBinding
。 这样,当我需要创建CommonLayoutBinding
时,我可以确保片段的绑定存在。
接下来我可以通过调用commonBinding = CommonLayoutBinding.bind(binding.getRoot());
创建一个CommonLayoutBinding
的实例。 . 请注意,来自具体片段绑定的根视图被传递给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()
做的那样。 在原则上,它仍然是从onCreateVIew()
调用的。 如上所述,此绑定从基础 class 使用。 我正在使用getCommonBinding()
来访问来自common_layout.xml
的视图。 BaseFragment 的每个子BaseFragment
现在都可以从ViewBinding
访问这些视图。
这样我就可以将所有基于通用视图的逻辑上移到基础 class。
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
)不仅有一个绑定 class ,它提供对视图层次结构中所有视图的访问如果视图不能移动到通用布局中怎么办?
我对如何将其作为最佳实践来解决非常感兴趣:让我们考虑一下:在具体的 ViewBinding 周围引入一个包装器ViewBinding
。 我们可以引入一个接口来提供对常用视图的访问。 从片段中,我们将绑定包装在这些包装类中。 另一方面,这将导致每个 ViewBinding 类型的许多包装器。 但是我们可以使用抽象方法(泛型)将这些包装器提供给BaseFragment
。 然后BaseFragment
能够访问视图或使用定义的接口方法处理它们。 你怎么看?
综上所述:
也许这只是 ViewBinding 的实际限制,一种布局需要拥有自己的 Binding 类。 如果您在无法共享布局并且需要在每个布局中声明重复的情况下找到了一个好的解决方案,请告诉我。
我不知道这是否是最佳实践,或者是否有更好的解决方案。 但是,直到这是我用例的唯一已知解决方案,这似乎是一个好的开始!
这是我的BaseViewBindingFragment
的完整示例:
abstract
属性或函数,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 年 2 月 4 日更新:我在研究并从许多来源获得灵感后写了一篇文章。 这篇文章将根据我未来在视图绑定方面的经验进行更新,因为我们公司现在已经放弃了近 80% 的合成绑定。
我还提出了一个有效地使用最终变量的 Base Class 解决方案。 我的主要目标是:
abstract fun getBind():T
, the child class could implement it and call it directly. I didn't wanted that as这将使保持基础 class 中的绑定毫无意义,我相信)所以就在这里。 首先是我的应用程序的当前结构。 这些活动不会自行膨胀,基础 class 会为他们做:
儿童活动和片段:
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()
}
正如您所看到的,儿童班总是很容易扩展,因为基础活动会完成所有繁重的工作。 并且由于合成材料被广泛使用,因此没有太大问题。 要使用具有前面提到的约束的绑定类,我会:
需要子类实现将数据提供回父片段的功能。 这很容易,只需创建更多返回子绑定类实例的抽象函数即可。
将子类的视图绑定存储在一个变量中(例如val binding:T
),以便基础 class 可以在销毁广告时相应地取消它处理生命周期。 有点棘手,因为事先不知道孩子的 Binding class 实例类型。 但是将父级设为通用( <T:ViewBinding>
)将完成这项工作
将视图返回给系统进行通货膨胀。 再次,很容易,因为谢天谢地,对于大多数组件,系统接受一个膨胀的视图,并且拥有孩子的绑定实例将让我向系统提供一个视图
防止子 class 直接使用在点 1 中创建的路线。 想一想:如果一个孩子 class 有一个 function getBind(){...}
返回他们自己的绑定 class 实例,他们为什么不使用它,而是使用super.binding
? 是什么阻止他们在 onDestroy() 中使用getBind()
function,而不应该访问绑定?
这就是为什么我将 function 设为 void 并将一个可变列表传入其中的原因。 子 class 现在会将其绑定添加到父将访问的列表中。 如果他们不这样做,它将抛出一个 NPE。 如果他们试图在销毁或其他地方使用它,它将再次抛出illegalstate exception
。 我还创建了一个方便的高阶 function 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))
}
}
我认为一个简单的反应是使用常见的 class 的bind
方法。
我知道这不适用于所有情况,但它适用于具有相似元素的视图。
如果我有两个布局row_type_1.xml
和row_type_2.xml
共享公共元素,那么我可以执行以下操作:
ROW_TYPE_1 -> CommonRowViewHolder(
RowType1Binding.inflate(LayoutInflater.from(parent.context), parent, false))
然后对于类型 2,不要创建另一个 ViewHolder 来接收它自己的绑定 class,而是执行以下操作:
ROW_TYPE_2 -> {
val type2Binding = RowType2Binding.inflate(LayoutInflater.from(parent.context), parent, false))
CommonRowViewHolder(RowType1Binding.bind(type2Binding))
}
如果它是组件的子集,则可以放置 inheritance
CommonRowViewHolder: ViewHolder {
fun bind(binding: RowType1Holder)
}
Type2RowViewHolder: CommonRowViewHolder {
fun bind(binding: RowType2Holder) {
super.bind(Type1RowViewHolder.bind(binding))
//perform specific views for type 2 binding ...
}
}
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
}
基本 Class 将 go 这样
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 中只需根据使用情况使用绑定
我创建了这个抽象的 class 作为基础;
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)
}
}
这是@Chetan's answer with usages的一个稍微不同的版本。
我添加了@CallSuper
注释并删除了类型转换。
ViewBindingActivity.kt
abstract class ViewBindingActivity<VB : ViewBinding> : AppCompatActivity() {
abstract val bindingInflater: (LayoutInflater) -> VB
private var _binding: VB? = null
protected val binding: VB get() = requireNotNull(_binding)
@CallSuper
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
_binding = bindingInflater.invoke(layoutInflater)
setContentView(binding.root)
}
override fun onDestroy() {
super.onDestroy()
_binding = null
}
}
ViewBindingFragment.kt
abstract class ViewBindingFragment<VB : ViewBinding>() : Fragment() {
protected abstract val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> VB
private var _binding: VB? = null
protected val binding: VB get() = requireNotNull(_binding)
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
}
}
活动
class HomeActivity : ViewBindingActivity<ActivityHomeBinding>() {
override val bindingInflater: (LayoutInflater) -> ActivityHomeBinding
get() = ActivityHomeBinding::inflate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
...
}
}
分段
class HomeFragment : ViewBindingFragment<FragmentHomeBinding>() {
override val bindingInflater: (LayoutInflater, ViewGroup?, Boolean) -> FragmentHomeBinding
get() = FragmentHomeBinding::inflate
}
您可以将 inflate 方法传递给抽象 class
class MainFragment :
BaseFragment<MainFragmentBinding>(MainFragmentBinding::inflate) { }
abstract class BaseFragment<T : ViewBinding>(
private val viewBindingInflater: (
inflater: LayoutInflater,
parent: ViewGroup?,
attachToParent: Boolean
) -> T
) : Fragment() {
lateinit var viewBinding: T
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
viewBinding = viewBindingInflater(inflater, container, false)
return viewBinding.root
}
}
这是对伟大的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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.