Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get included views with Android Databinding?

I'm playing with Android databinding library and I'm trying to use it with included layouts.

The code I have is like this:

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 have written in comments the view myView which is declared in an "included" layout is not visible. If I replace the with the actual code in the view.xml then mBinding.myView becomes visible, the cause seems to be the include then.

The official documentation states only that

"Data binding does not support include as a direct child of a merge element." but in my case View is a child of LinearLayout, it's not a direct child..

Any hints?

like image 990
Luca S. Avatar asked Oct 20 '15 09:10

Luca S.


1 Answers

You need to provide an ID to 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, the include will be a generated Binding. For example, if view.xml is:

<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 a ViewBinding class:

View myView = mBinding.included.myView;
like image 160
George Mount Avatar answered Oct 18 '22 08:10

George Mount