<include - onclick 取决于包含

<include - onclick depending the include

我正在尝试在其他布局中重新使用带有按钮的布局,但我希望按钮的布局对于包含的每个不同布局都有不同的点击侦听器。有什么想法吗?

第一个布局

    <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}" />

包含的布局

<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"/>

如果你为此使用一个接口会更好。像这样:

interface IncludedClickListener {
    void onClick();
}

然后在你的 included_layout.xml:

<data>
    <variable
        name="clickHandler"
        type="somepackage.IncludedClickListener " />
</data>

<Button
    ...
    android:onClick="@{() -> clickHandler.onClick()"/>

然后修改CurrencieViewModelCalculatorViewModel实现IncludedClickListener。然后像以前一样使用它:

<include 
    layout="@layout/buttons"
    bind:clickHandler="@{model}" />