简体   繁体   中英

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
        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()} .

What you could do is pass the Activity in the databinding as a variable, ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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