ViewBinding遇上include和merge怎么办?

include

这个处理起来比较简单,假设布局layout1includelayout2,可以这样写:

layout1.xml

1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include
android:id="@+id/layout2"
layout="@layout/layout2" />
</LinearLayout>

layout2.xml

1
2
3
4
5
6
7
8
9
10
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<TextView
android:id="@+id/tvContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>

我们要怎么拿到layout2tvContent呢?如下:

1
2
val layout1Binding = Layout1Binding.inflate(layoutInflater)
layout1Binding.layout2.tvContent.text = "Hello, World!"

merge

如下给layout2加入merge标签,然后必须把layout1includeid移除掉,否则会造成应用崩溃。使用merge的好处就是减少了一层布局嵌套,相当于直接把merge里面的内容填充到了include的位置。

layout1.xml

1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<include layout="@layout/layout2" />
</LinearLayout>

layout2.xml

1
2
3
4
5
6
7
8
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android">

<TextView
android:id="@+id/tvContent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</merge>

其实这也不麻烦,使用bind方法把两个绑定类对象关联起来即可。

1
2
3
val layout1Binding = Layout1Binding.inflate(layoutInflater)
val layout2Binding = Layout2Binding.bind(layout1Binding.root)
layout2Binding.tvContent.text = "Hello, World!"
作者

EIong

发布于

2022-07-20

更新于

2022-07-20

许可协议