Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android data-binding - Can I access the enclosing activity in the layout XML?

I'd like to define an event listener in the XML that finishes the enclosing activity, like this:

<EditText
    android:id="@+id/finish"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:onEditorAction="@{() -> activity.finish()}" />

However, I don't have a reference to the enclosing activity. I know I can pass it using a <variable>, but Activity seems a too common variable to be explicitly passed in every layout... I thought data-binding was introduced to simplify code. I didn't find any hint in the ViewDataBinding class.

like image 603
Avi Avatar asked Jul 24 '16 11:07

Avi


1 Answers

You can access the context, but it isn't automatically cast to an Activity. It makes sense that if the inflation context is an Activity that you could retrieve it automatically as a variable. You can add a feature request on android.com for that.

In the mean time, I know it is a bit longer, but you can do this as long as the inflation context is an Activity:

<EditText
    android:id="@+id/finish"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:imeOptions="actionDone"
    android:inputType="text"
    android:onEditorAction="@{() -> ((Activity)context).finish()}" />
like image 89
George Mount Avatar answered Sep 27 '22 16:09

George Mount