是否可以通过XML中的数据绑定完成一个Activity?

Is it possible to finish an Activity through data binding in the XML?

我在 activity 中有一个 ImageView(后退按钮),我想通过在 XML 本身中使用数据绑定来完成 Activity:

<ImageView
        android:id="@id/ImageView_fromAddItemActivity_BackIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginStart="16dp"
        android:layout_marginTop="8dp"
        android:onClick = "@{ finish()}"
        app:srcCompat="@drawable/ic_back_dark"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

但是没用。有人知道这是否可能吗?

要使 onClick() 正常工作,您需要使用以下符号:android:onClick=@{() -> function()}

你可以做的是将数据绑定中的 Activity 作为变量传递,即

<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
        <variable
            name="activity"
            type="android.app.activity" />
    </data>
    <ConstraintLayout... /> <!-- UI layout's root element -->
</layout>

然后activity.finish()。我不会那样做,因为您将上下文与数据绑定紧密耦合。您可以改为通过可以绑定的 viewmodel,然后通过它执行 finish()。