引用InverseBindingAdapter中的另一个属性

时间:2017-07-28 19:51:00

标签: android android-databinding

对于显示日期的BindingAdapter,我有以下TextView

@BindingAdapter(value = {"date", "minDate", "maxDate", "dateFormat", "dateAttrChanged"}, requireAll = false)
public static void bindDate(TextView textView, Long date, Long minDate, Long maxDate,
                            String dateFormat, final InverseBindingListener dateChangedListener) {
    DateFormat dateFormatter = new SimpleDateFormat(dateFormat != null? dateFormat : "dd.MM.yyyy", Locale.GERMAN);
    textView.setOnClickListener(view -> {
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(date != null ? date : System.currentTimeMillis());
        DatePickerDialog datePickerDialog = new DatePickerDialog(textView.getContext(), (dateView, year, month, dayOfMonth) -> {
            Calendar result = Calendar.getInstance();
            result.set(year, month, dayOfMonth);
            textView.setText(dateFormatter.format(result.getTimeInMillis()));
            if(dateChangedListener != null) {
                dateChangedListener.onChange();
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        if(minDate != null) {
            datePickerDialog.getDatePicker().setMinDate(minDate);
        }
        if(maxDate != null){
            datePickerDialog.getDatePicker().setMaxDate(maxDate);
        }
        datePickerDialog.show();
    });
    textView.setClickable(true);
    textView.setFocusable(true);
    if(date != null) {
        textView.setText(dateFormatter.format(date));
    }

    // todo find a way to pass the dateFormat to InverseBindingAdapter
    textView.setTag(dateFormat);
}

@Nullable
@InverseBindingAdapter(attribute = "date", event = "dateAttrChanged")
public static Long bindDate(TextView textView) {
    DateFormat dateFormatter = new SimpleDateFormat(textView.getTag() != null ?
            (String) textView.getTag() : "dd.MM.yyyy", Locale.GERMAN);
    Long result = null;
    try {
        result = dateFormatter.parse(String.valueOf(textView.getText())).getTime();
    } catch (Throwable t) {
        t.printStackTrace();
    }
    return result;
}

有没有办法在dateFormat中引用InverseBindingAdapter属性(通过标记传递它的值是当前的解决方法)?

0 个答案:

没有答案