I am trying to re-use a layout with buttons inside others layouts but I want the layout of the buttons to have different on click listeners for every different layout that is included. Any idea?
First layout
<data>
<variable
name="model"
type="com.example.calculator.viewmodel.CalculatorViewModel" />
</data>
<include layout="@layout/buttons"
bind:var="@{model}" />
secondView
<data>
<variable
name="variable"
type="com.example.calculator.viewmodel.CurrencieViewModel" />
</data>
<include
layout="@layout/buttons"
bind:currencies="@{variable}" />
the included layout
<data>
<variable
name="var"
type="com.example.calculator.viewmodel.CalculatorViewModel" />
<variable
name="currencies"
type="com.example.calculator.viewmodel.CurrencieViewModel" />
</data>
...
<Button
android:id="@+id/btn_0"
android:layout_width="97dp"
android:layout_height="100dp"
android:layout_row="4"
android:layout_column="1"
android:background="@color/white"
android:text="0"
android:textColor="@color/iconsColor"
android:textSize="50dp"
android:onClick="@{() -> depent the viewmodel different fuction"/>
It is better if you use an interface for this. Something like this:
interface IncludedClickListener {
void onClick();
}
and then inside your included_layout.xml
:
<data>
<variable
name="clickHandler"
type="somepackage.IncludedClickListener " />
</data>
<Button
...
android:onClick="@{() -> clickHandler.onClick()"/>
and then modify CurrencieViewModel
and CalculatorViewModel
implement IncludedClickListener
. Then use it like before:
<include
layout="@layout/buttons"
bind:clickHandler="@{model}" />