android data binding <include> layout OnClick listener doesn't work
If you want to use DataBinding
variables in an included layout, you need to pass them to the included layout, and also make your parent view use DataBinding
:
<layout>
<data>
<variable type="your.packages.here.MainActivity" name="listener"/>
</data>
<FrameLayout>
<include
android:id="@+id/included"
layout="@layout/global_actions"
app:listener="@{listener}"/>
</include>
</FrameLayout>
</layout>
You need to set your listener in your MainActivity.class to the corresponding binding class:
activityMainBinding.setListener(this);
and in your included layout, you need to use the same name that you used in your parent layout (app:listener
):
<layout>
<data>
<variable type="your.packages.here.MainActivity" name="listener"/>
</data>
<ImageButton
android:onClick="@{listener::onClickState}"/>
</layout>
Please take a look at George Mounts answer to a similiar question.
Activity:
activityMainBinding.included.setListener(this);
global_actions.xml::
<layout>
<data>
<variable type="your.packages.here.MainActivity" name="listener"/>
</data>
<ImageButton
android:id="@+id/settingsButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:src="@drawable/ic_settings_black_36dp"
android:layout_gravity="end"
android:background="@color/colorToolBar"
android:layout_margin="4dp"
android:layout_marginLeft="20dp"
android:onClick="@{listener::onClickState}"
android:alpha="0.4"/>
</layout>