Easy Complete Example
Just set id
to included layout, and use binding.includedLayout.anyView
.
This example helps passing a value to <include
& accessing included views in code.
Step 1
You have layout_common.xml
, want to pass String
to included layout.
You will create String
variable in layout and refer this String
to TextView
.
<data>
// declare fields
<variable
name="passedText"
type="String"/>
</data>
<TextView
android:id="@+id/textView"
...
android:text="@{passedText}"/> //set field to your view.
Step 2
Include this layout to parent layout. Give an id
to included layout, so that we can use that in binding class. Now you can pass String passedText
to your <include
tag.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<layout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<LinearLayout
..
>
<include
android:id="@+id/includedLayout"
layout="@layout/layout_common"
app:passedText="@{@string/app_name}" // here we pass any String
/>
</LinearLayout>
</layout>
- You can use now
binding.includedLayout.textView
in your class.
You can pass any variables to included layout like above.
ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
binding.includedLayout.textView.setText("text");
Note Both layouts (parent & included) should be binding layout
, wrapped with <layout