关于如何从数据绑定android获取上下文的完整示例或教程 [英] Full example or tutorial about how to get Context from data binding android

查看:264
本文介绍了关于如何从数据绑定android获取上下文的完整示例或教程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Android的初学者。我有一个这样的问题
Android DataBinding在哪里获取上下文?
需要通过正确的方式获取格式化textview的日期和时间的数据绑定的上下文。但是我不明白答案。任何人都可以帮助我从正确的方式获取数据绑定的上下文。

解决方案

格式化日期和时间的最佳方式是使用String格式。例如,您可以使用以下内容:

 < TextView android:text =@ {@ string / dateFormat(user.birthday )}... /> 

dateFormat是一个这样的资源:

 < string name =dateFormat>%1 $ td /%1 $ tm /%1 $ tY< / string> 

生日很长。您应该查看有关更多格式信息的日期格式化程序文档相关的时间和日期。



Android DataBinding在哪里获取上下文?,我给了一个选项,但暗示了一个现在也可用。您可以使用内置的上下文变量,它是根视图的上下文:

 < TextView android:text =@ {Converters.formatDate(context,user.birthday,dateFlags)}... /> 

然后你的Converters类会有这样的东西:

  public class Converters {
public static String formatDate(Context context,long timeMillis,int dateFlags){
return DateUtils.formatDateTime(view.getContext ,timeMillis,
dateFlags)
}
}

但是我推荐第一个,因为它是容易,灵活,并使用较少的代码。它不会将日期和时间格式修复到单个区域设置。


I'm a beginner in android. I have a problem like this issue Android DataBinding where to get context? Need to get context for formatting date and time of textview with data binding in correctly ways. However I don't understand the answer clearly. Anyone helps me to get context from data binding in correctly ways.

解决方案

The best way to format date and time is with String formatting. For example, you can use this:

<TextView android:text="@{@string/dateFormat(user.birthday)}" .../>

Where the dateFormat is a resource like this:

<string name="dateFormat">%1$td/%1$tm/%1$tY</string>

And the birthday is a long. You should look at the date formatter documentation for more formatting information related to time and date.

In Android DataBinding where to get context?, I gave one option, but hinted at one that is now also available. You may use the built-in context variable, which is the Context of the root View:

<TextView android:text="@{Converters.formatDate(context, user.birthday, dateFlags)}" .../>

Then your Converters class would have something like this:

public class Converters {
    public static String formatDate(Context context, long timeMillis, int dateFlags) {
        return DateUtils.formatDateTime(view.getContext(), timeMillis,
             dateFlags)
    }
}

But I recommend the first as it is easy, flexible, and uses less code. It doesn't fix your date and time formats to a single locale.

这篇关于关于如何从数据绑定android获取上下文的完整示例或教程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆