create different InverseBindingAdapter for Short and Integer values on android:text of EditText

人走茶凉 提交于 2019-12-12 04:55:28

问题


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:


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;
    }
}


来源:https://stackoverflow.com/questions/44947467/create-different-inversebindingadapter-for-short-and-integer-values-on-androidt

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