且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Android数据绑定上的自定义XML属性

更新时间:2022-11-19 21:34:17

您不需要任何特殊的操作即可分配给OnItemSelectedListener:

You don't need anything special to assign to the OnItemSelectedListener:

<android.support.v7.widget.AppCompatSpinner
    android:id="@+id/spn_status"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/chk_installed"
    android:onItemSelectedListener="@{myItemSelectedListener}"
    apps:adapter="@{statusAdapter}"/>

以上假设 myItemSelectedListener 您的布局中的变量e键入 OnItemSelectedListener

The above assumes a myItemSelectedListener variable in your layout of the type OnItemSelectedListener.

如果只想使用onItemSelected或onNothingSelected,则可以在布局已经存在:

If you want to use only the onItemSelected or onNothingSelected, you can use the attribute in your layout already:

<android.support.v7.widget.AppCompatSpinner
    android:id="@+id/spn_status"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_below="@+id/chk_installed"
    android:onItemSelected="@{handler::onItemSelected}"
    apps:adapter="@{statusAdapter}"/>

这里假定处理程序的方法类:

public class Handler {
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        //...
    }
}

您还可以使用lambda表达式:

You can also use a lambda expression:

android:onItemSelected="@{(p, v, pos, id) -> handler.onItemSelected(v, pos)}"

这里,处理程序的类有一个方法:

Here, handler's class has a method:

public class Handler {
    public void onItemSelected(View view, int position) {
        //...
    }
}

在所有这些情况下,您都必须分配 onCreateView 中的处理程序或侦听器,就像您使用 binding.setHandler(...)进行上述操作一样>致电。您不需要调用 lAppCompatSpinner.setOnItemSelectedListener(...),因为它将作为绑定的一部分完成。

In all these cases, you must assign the handler or listener in the onCreateView, just as you're doing above with the binding.setHandler(...) call. You don't need to call lAppCompatSpinner.setOnItemSelectedListener(...) because it will be done as part of the binding.