在android:EditText的文本上为Short和Integer值创建不同的InverseBindingAdapter [英] create different InverseBindingAdapter for Short and Integer values on android:text of EditText

查看:150
本文介绍了在android:EditText的文本上为Short和Integer值创建不同的InverseBindingAdapter的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我为自定义数据绑定创建了这些方法

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

并将我的Short和Integer变量绑定到视图。当我构建项目时,自动生成的Java使用前三种方法,而第四种方法( getIntText )没有使用,问题就在这里。它对整数字段使用 getShortText 并导致编译时间 casting 错误。

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.

我很惊讶,数据绑定器正确检测到它应该使用 setIntText 来将Integer值设置为视图,但是它可以

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.

如何解决此问题?

请注意,我不喜欢使用以下技术,因为当数据为空时我想控制绑定

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}


推荐答案

我找到了解决方案,但是
我将 getIntText 的返回值从 Integer 更改为 int ,问题解决了。
如果有人找到其他更好的解决方案,请告诉我。

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

这篇关于在android:EditText的文本上为Short和Integer值创建不同的InverseBindingAdapter的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆