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 Date
from my timeInMillis
value.
Data Binding allows you to effortlessly communicate across views and data sources. This pattern is important for many Android designs, including model view ViewModel (MVVM), which is currently one of the most common Android architecture patterns.
The Data Binding Library is a support library that allows you to bind UI components in your layouts to data sources in your app using a declarative format rather than programmatically. Layouts are often defined in activities with code that calls UI framework methods.
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}"
/>
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)}" />
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With