Getting Date from getTimeInMillis when using Databinding

强颜欢笑 提交于 2019-12-10 12:55:04

问题


I have a timeInMillis value, which I know I can get a Date from with something like;

SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
String dateString = formatter.format(new Date(dateInMillis)));

I'm using DataBinding to populate a RecyclerView. I am also aware that I can manipulate strings when using DataBinding with something like this;

android:text='@{String.format("%.1f", example.double)}'

However, I cannot work out how to populate the TextView with a formatted Datefrom my timeInMillis value.


回答1:


You can add in your model a function which it can transform your timeInMillis to a formatted Date.

In your model used in dataBinding layout :

public String getDateFormatted(){
    SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy"); 
    return formatter.format(new Date(dateInMillis)));;
}

In your layout :

<layout>
   <data>
      <variable name="yourModel"
                type="com.example.model.yourModel"/>
   </data>
...
<TextView 
...
   android:text="@{yourModel.dateFomatted}"
/>



回答2:


I think that putting the format in resources is best approach:

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

And you would bind the value to the resource like this:

<TextView ... android:text="@{@string/format(model.date)}" />


来源:https://stackoverflow.com/questions/42596831/getting-date-from-gettimeinmillis-when-using-databinding

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