简体   繁体   English

Android数据绑定 - 我可以访问布局XML中的封闭活动吗?

[英]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: 我想在XML中定义一个完成封闭活动的事件监听器,如下所示:

<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. 我知道我可以使用<variable>传递它,但是Activity似乎是一个太常见的变量,无法在每个布局中显式传递...我认为数据绑定是为了简化代码而引入的。 I didn't find any hint in the ViewDataBinding class. 我没有在ViewDataBinding类中找到任何提示。

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. 您可以在android.com上添加功能请求。

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()}" />

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

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