DatePicker day, month & year attributes for two-way data binding missing?

Viewed 1410

I want to get the selected date of a DatePicker via two-way data binding. Following this guide from Google, there should be three attributes for my DatePicker,

android:year
android:month
android:day

which are intended for the two-way data binding.

However, those attributes do not appear for my DatePicker.

Am I missing out on some dependency, maybe? How can I get the selected date, using two-way data binding?

This is the DatePickers XML:

<DatePicker
    android:id="@+id/date_picker"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:calendarViewShown="false"
    android:datePickerMode="spinner"
    app:layout_constraintEnd_toEndOf="@id/guideline_end"
    app:layout_constraintStart_toStartOf="@id/guideline_start"
    app:layout_constraintTop_toTopOf="@id/guideline_top"
    />
2 Answers

What I've done to check your problem (still I see message about unknown attribute as well, but except that there no problem):

In XML:

<DatePicker
     android:layout_width="wrap_content"
     android:datePickerMode="spinner"
     android:year="@={viewModel.year}"
     android:month="@={viewModel.month}"
     android:day="@={viewModel.day}"
     android:onDateChanged="@{(v, year, month, day) -> viewModel.onDateChanged(year, month, day)}"
     android:layout_height="wrap_content"/>

In ViewModel:

var year: MutableLiveData<Int> = MutableLiveData(2020)
var month: MutableLiveData<Int> = MutableLiveData(5)
var day: MutableLiveData<Int> = MutableLiveData(22)

fun onDateChanged(year: Int, month: Int, day: Int){
    Log.v("Test_Picker", "$year $month $day")
}

So after date's change ViewModel's onDateChanged invokes and I can observe changes of LiveData's year/month/day in Fragment

you can get the data from the listener:

 date_picker.setOnDateChangedListener { datePicker, year, month, day ->

       Log.v("Rene", "Year: $year Month: $month Day: $day")

 }

Or directly calling the DatePicker

  date_picker.dayOfMonth
  date_picker.month
  date_picker.year
Related