Android DataBinding 从哪里获取上下文?
Android DataBinding where to get context?
我有 TextView
显示时间。我想使用 Android 的 DataBinding 插件。
对于格式化时间,我正在使用 DateUtils.formatDateTime(context, int, int)
方法,该方法采用 Context
实例。是否有可能获得上下文包含元素?还是我必须使用老派的方式?
谢谢
认为我应该回答而不是发表评论。当 rc2 发布时,您将有更多选择。在 rc1 中,您可以将变量中的上下文传递给 Binding,然后将其作为参数传递给方法。或者,您可以为数据绑定创建自定义属性:
@BindingAdapter({"timeMillis", "dateFlags"})
public static void setDateText(TextView view, int timeMillis, int dateFlags) {
view.setText(DateUtils.formatDateTime(view.getContext(), timeMillis,
dateFlags));
}
然后在您的 TextView 中使用它:
<TextView ... app:timeMillis="@{timeVar}" app:dateFlags="@{dateFlags}"/>
您也可以使用当前视图 context
作为参数在您的视图中执行类似的操作。
...
android:text="@{yourModelHere.yourModelMethodHere(context)}"
...
A special variable named context is generated for use in binding
expressions as needed. The value for context is the Context from the
root View's getContext(). The context variable will be overridden by
an explicit variable declaration with that name.
换句话说,每次需要传递上下文时,只需使用 "context",如 @{Object.method(context)}
.
要使用字符串资源,请使用此
this.yourView.getRoot().getResources().getString(R.string.your_string)
我有 TextView
显示时间。我想使用 Android 的 DataBinding 插件。
对于格式化时间,我正在使用 DateUtils.formatDateTime(context, int, int)
方法,该方法采用 Context
实例。是否有可能获得上下文包含元素?还是我必须使用老派的方式?
谢谢
认为我应该回答而不是发表评论。当 rc2 发布时,您将有更多选择。在 rc1 中,您可以将变量中的上下文传递给 Binding,然后将其作为参数传递给方法。或者,您可以为数据绑定创建自定义属性:
@BindingAdapter({"timeMillis", "dateFlags"})
public static void setDateText(TextView view, int timeMillis, int dateFlags) {
view.setText(DateUtils.formatDateTime(view.getContext(), timeMillis,
dateFlags));
}
然后在您的 TextView 中使用它:
<TextView ... app:timeMillis="@{timeVar}" app:dateFlags="@{dateFlags}"/>
您也可以使用当前视图 context
作为参数在您的视图中执行类似的操作。
...
android:text="@{yourModelHere.yourModelMethodHere(context)}"
...
A special variable named context is generated for use in binding expressions as needed. The value for context is the Context from the root View's getContext(). The context variable will be overridden by an explicit variable declaration with that name.
换句话说,每次需要传递上下文时,只需使用 "context",如 @{Object.method(context)}
.
要使用字符串资源,请使用此
this.yourView.getRoot().getResources().getString(R.string.your_string)