Using CalendarView with databinding

巧了我就是萌 提交于 2019-12-01 11:23:04

There are bunch of bugs, which I found after tracking all classes.

Bug 1

This is bug of Android Documentation. See CalendarViewBindingAdapter class.

You can see they have created binding adapter for android:date, but there is no @InverseBindingAdapter.

@BindingAdapter({"android:date"})
public static void setDate(CalendarView view, long date) {
    if (view.getDate() != date) {
        view.setDate(date);
    }
}

// no @InverseBindingAdapter written

But on documentation, they have written that CalendarView supports two-way binding.

Perhaps we will get this in next updates.

I also tried to add @InverseBindingAdapter but that was not working too.

@InverseBindingAdapter(attribute = "android:date", event = "android:dateAttrChanged")
public static long getDateLong(CalendarView view) {
    return view.getDate();
}

Bug 2

Try setting setOnDateChangeListener on CalendarView, you will get same date always.

Below does not work

binding.cal.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
     Log.d(TAG, "aLong: " + new Date(view.getDate()).toString());
});

Below works

binding.cal.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
    Log.d(TAG, "aLong: " + new Date(year, month, dayOfMonth).toString());
});

That's why my @InverseBindingAdapter does not work.

Because calendarView.getDate() is not giving correct date.

Fix

You can fix this by creating your adapter till they don't fix this issue. Just put below class in your project, and everything will work well.

public class CalendarViewBindingAdapter {
    @BindingAdapter(value = {"android:onSelectedDayChange", "android:dateAttrChanged"},
            requireAll = false)
    public static void setListeners(CalendarView view, final CalendarView.OnDateChangeListener onDayChange,
                                    final InverseBindingListener attrChange) {
        if (attrChange == null) {
            view.setOnDateChangeListener(onDayChange);
        } else {
            view.setOnDateChangeListener(new CalendarView.OnDateChangeListener() {
                @Override
                public void onSelectedDayChange(CalendarView view, int year, int month,
                                                int dayOfMonth) {
                    if (onDayChange != null) {
                        onDayChange.onSelectedDayChange(view, year, month, dayOfMonth);
                    }
                    Calendar instance = Calendar.getInstance();
                    instance.set(year, month, dayOfMonth);
                    view.setDate(instance.getTimeInMillis());
                    attrChange.onChange();
                }
            });
        }
    }
}

What I fixed

I just set date to CalendarView (view.setDate()), which was 0 previously.

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