How to get included views with Android Databinding?

I am playing with the Android databinding library , and I am trying to use it with the included layouts.

The code I have is as follows:

activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:bind="http://schemas.android.com/apk/res-auto"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id = "@+id/linearLayout"> <include layout="@layout/view" /> </LinearLayout> </layout> 

view.xml

 <View xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:id = "@+id/myView"> </View> 

MainActivity.java

 public MainActivity extends AppCompatActivity{ private ActivityMainBinding mBinding; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mBinding = DataBindingUtil.setContentView(this, R.layout.activity_main); LinearLayout layout = mBinding.linearLayout; // this field is visible View myView = mBinding.myView // THIS FIELD IS NOT VISIBLE } } 

As I wrote in the comments, the view myView declared in the "included" layout is not displayed. If I replace the actual code in view.xml, then mBinding.myView will become visible, therefore the inclusion will be the reason.

The official documentation only states that

"Data binding does not support inclusion as a direct merge child." but in my case, View is a LinearLayout child, it is not a direct child.

Any clues?

+6
source share
1 answer

You need to specify the identifier of the include statement:

 <include android:id="@+id/included" layout="@layout/view" /> 

Now you can access the include view:

 View myView = mBinding.included; 

If your included layout is a binding layout, include will be the generated Binding. For example, if view.xml:

 <layout xmlns:android="http://schemas.android.com/apk/res/android"> <View android:layout_width="match_parent" android:layout_height="match_parent" android:background="@{@android:color/black}" android:id="@+id/myView"/> </layout> 

then the layout field will be the ViewBinding class:

 View myView = mBinding.included.myView; 
+14
source

All Articles