问题描述
我是DataBinding概念的新手。我看过一些教程,但是看到这些我感到困惑。任何人都可以给我一个想法,如何使用setOnClickListener
或任何其他使用DataBinding的视图(例如Button)侦听器。预先感谢。
button.setOnClickListener(View v){......} 需要在dataBinding中使用以上功能。谁能帮我。
解决方法
如果您正在使用数据绑定,那么很可能您正在使用某种视图模型,如果这样做,则可以执行类似的操作,但是该概念可以应用于任何其他变量。
您的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()
}