问题
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