简体   繁体   English

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

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

I have an ImageView (A back button) inside an activity and i want to finish the Activity by using data binding in the XML itself as such:我在活动中有一个 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"/>

But it doesn't work.但它不起作用。 Anyone has an idea whether this is possible ?任何人都知道这是否可能?

For onClick() to work you need to use the following notation: android:onClick=@{() -> function()} .要使onClick()工作,您需要使用以下符号: android:onClick=@{() -> function()}

What you could do is pass the Activity in the databinding as a variable, ie您可以做的是将数据绑定中的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>

then do activity.finish() .然后做activity.finish() I wouldn't do it that way though since you are tightly coupling the context with the data binding.我不会那样做,因为您将上下文与数据绑定紧密耦合。 You could instead go through a viewmodel which you can bind, then do the finish() through it.您可以改为通过可以绑定的viewmodel模型,然后通过它执行 finish() 。

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

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