Full example or tutorial about how to get Context from data binding android [closed]

老子叫甜甜 提交于 2019-12-14 03:31:26

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/42881529/full-example-or-tutorial-about-how-to-get-context-from-data-binding-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!