create different InverseBindingAdapter for Short a

2019-09-15 17:56发布

I create these methods for custom data binding

@BindingAdapter("android:text")
public static void setShortText(TextView view, short value) {
    view.setText(String.valueOf(value));
}

@InverseBindingAdapter(attribute = "android:text")
public static Short getShortText(TextView view) {
    try {
        return Short.parseShort(view.getText().toString());
    } catch (NumberFormatException e) {
        return null;
    }
}

@BindingAdapter("android:text")
public static void setIntText(TextView view, int value) {
    view.setText(String.valueOf(value));
}

@InverseBindingAdapter(attribute = "android:text")
public static Integer getIntText(TextView view) {
    try {
        return Integer.parseInt(view.getText().toString());
    } catch (NumberFormatException e) {
        return null;
    }
}

and bind my Short and Integer variables to views. when I build my project, the auto generated java uses the first three methods and it's have no usage from the fourth one (getIntText), and the problem is here. it use getShortText for Integer fields and cause compile time casting error.

I'm surprised, data binder properly detect it should use setIntText for set Integer values to views but it can't recognize that for inverseBinding.

how can I fix the problem?

please note that I prefer not use from below technique because I want to have control on binding when data in null

android:text="@={`` + obj.field}

1条回答
趁早两清
2楼-- · 2019-09-15 18:19

I find a solution, but really not satisfy myself. I change getIntText return value from Integer to int and problem is solved. if someone find other better solution please let me know.

@InverseBindingAdapter(attribute = "android:text")
public static int getIntText(TextView view) {
    try {
        return Integer.parseInt(view.getText().toString());
    } catch (NumberFormatException e) {
        return -1;
    }
}
查看更多
登录 后发表回答