如何为数据绑定中的视图设置监听器功能(如 setOnClickListener)

How to set a listener functionality (like setOnClickListener) for a view in dataBinding

我是 DataBinding 概念的新手。我看过一些教程,但看到这些我很困惑。谁能告诉我如何使用 setOnClickListener 或任何其他使用 DataBinding 的视图(例如 Button)的侦听器。提前致谢。

button.setOnClickListener(查看v){......} 需要在数据绑定中使用上述功能。谁能帮帮我。

如果您使用的是 Data-Binding,那么很可能您使用的是某些视图模型,如果是这样,那么请执行类似的操作,但这个概念可以应用于任何其他变量。

你的 xml 可能看起来像这样。

<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <data>

        <variable
            name="viewModel"
            type="com.example.MyViewModel" />
    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:paddingStart="16dp"
        android:paddingEnd="16dp">

     <!--other views-->

        <Button
                android:id="@+id/btnOkay"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="8dp"
                android:layout_marginTop="16dp"
                android:layout_marginEnd="15dp"
                android:layout_marginBottom="16dp"
                android:textColor="@color/pdp_black"
                app:layout_constraintBottom_toBottomOf="parent"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintTop_toTopOf="parent"
                app:onClick="@{() -> viewModel.onClickOkay()}" />

    </androidx.constraintlayout.widget.ConstraintLayout>

</layout>

并在您的视图模型中添加类似这样的内容以接收回调。

fun onClickOkay(){
    //from here use some interface to or some live data to notify the view attached with this view model to indicate the click happened in view.
  mutableLiveData.value = true
  //or 
  clickListener.onClick()
}