Full example or tutorial about how to get Context

2019-10-18 16:35发布

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条回答
干净又极端
2楼-- · 2019-10-18 17:07

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.

查看更多
登录 后发表回答