6

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.

Avi
  • 826
  • 6
  • 16

1 Answers1

2

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()}" />
George Mount
  • 20,708
  • 2
  • 73
  • 61
  • I tried to do just that, but the parentheses are misinterpreted by the parser and are translated to: (Activity) (getRoot().getContext()).finish(); on which compilation fails with "error: not a statement". – Avi Jul 25 '16 at 13:06
  • Actually, this kind of cast works for other variables. Only the built-in "context" causes this problem. – Avi Jul 28 '16 at 06:37
  • 7
    Is that good practice to pass Activity/fragment to the layout? – mertsimsek Jun 07 '18 at 11:53
  • btw, `context` can be `ContextThemeWrapper` and not `Activity` – logcat Jan 13 '20 at 13:10