ViewBinding-如何获取包含布局的绑定? [英] ViewBinding - how to get binding for included layouts?
本文介绍了ViewBinding-如何获取包含布局的绑定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在使用ViewBinding时,我遇到了一些未记录的案例.
While working with ViewBinding I come across few not documented cases.
第一:如何获取包含的通用视图布局部件的绑定,主绑定仅查看主布局中的项目?
First: How to get binding for included generic view layout parts, main binding see only items in main layout?
第二:如何为包含的合并类型布局部件获取绑定,再次主绑定仅查看主布局中的项目?
Second: How to get binding for included merge type layout parts, again main binding see only items in main layout?
推荐答案
在以下情况下
- 包含通用布局(不是合并节点),我们需要为包含的部分分配ID,这样在绑定中,我们将可以访问包含的子部分
<include
android:id="@+id/your_id"
layout="@layout/some_layout" />
通过这种方式输入您的活动代码:
This way in your activity code:
private lateinit var exampleBinding: ActivityExampleBinding //activity_example.xml layout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
exampleBinding = ActivityExampleBinding.inflate(layoutInflater)
setContentView(exampleBinding.root)
//we will be able to access included layouts view like this
val includedView: View = exampleBinding.yourId.idOfIncludedView
//[...]
}
- 在外部布局中包含合并块.我们无法向其中添加ID,因为合并块不是视图. 假设我们有这样的永久合并布局(merge_layout.xm):
- Include with merge block in external layout. We can't add ID to it because merge block is not a view. Let's say we have such eternal merge layout (merge_layout.xm):
<?xml version="1.0" encoding="utf-8"?>
<merge 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"
tools:showIn="@layout/activity_example">
<TextView
android:id="@+id/some_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World" />
</merge>
要正确绑定这种合并布局,我们需要:
To properly bind such merge layout we need to:
在您的活动代码中:
private lateinit var exampleBinding: ActivityExampleBinding //activity_example.xml layout
private lateinit var mergeBinding: MergeLayoutBinding //merge_layout.xml layout
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
exampleBinding = ActivityExampleBinding.inflate(layoutInflater)
//we need to bind the root layout with our binder for external layout
mergeBinding = MergeLayoutBinding.bind(exampleBinding.root)
setContentView(exampleBinding.root)
//we will be able to access included in merge layout views like this
val mergedView: View = mergeBinding.someView
//[...]
}
这篇关于ViewBinding-如何获取包含布局的绑定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文