include
这个处理起来比较简单,假设布局layout1
includelayout2
,可以这样写:
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>
|
我们要怎么拿到layout2
的tvContent
呢?如下:
1 2
| val layout1Binding = Layout1Binding.inflate(layoutInflater) layout1Binding.layout2.tvContent.text = "Hello, World!"
|
merge
如下给layout2
加入merge
标签,然后必须把layout1
中include
的id
移除掉,否则会造成应用崩溃。使用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!"
|