繁体   English   中英

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

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

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

<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() 。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM