android双向绑定,如何正确地将数字双向绑定到Android editText

我的方法是使用Handles延迟notifyPropertyChanged方法调用.以这种方式,当用户键入时,代码不运行,然后在用户停止键入最后一个字符后2.5秒,将调用notificationPropertyChanged.

视觉效果很酷,用户可以随意编写数字.

看这两个例子:

使用可以为每个字段使用此紧凑(?)代码:

//

// g1FuelCostYear field

//

private double g1FuelCostYear;

@Bindable

public String getG1FuelCostYear() {

return Double.valueOf(g1FuelCostYear).toString();

}

private Handler hG1FuelCostYearDelay = null;

public void setG1FuelCostYear(String g1FuelCostYear) {

// Delayed notification hadler creation

if (hG1FuelCostYearDelay == null) {

hG1FuelCostYearDelay = new Handler() {

@Override

public void handleMessage(Message msg) {

notifyPropertyChanged(it.techgest.airetcc2.BR.g1FuelCostYear);

}

};

} else {

// For each call remove pending notifications

hG1FuelCostYearDelay.removeCallbacksAndMessages(null);

}

// Data conversion logic

try {

this.g1FuelCostYear = Double.parseDouble(g1FuelCostYear);

}

catch (Exception ex) {

this.g1FuelCostYear = 0.0;

log(ex);

}

// New delayed field notification (other old notifications are removed before)

hG1FuelCostYearDelay.sendEmptyMessageDelayed(0,2500);

}

当您使用货币转换器或百分比转换器时,此代码非常有用.用户可以写一个普通的double,代码转换为货币字符串.如果使用货币字符串调用setter,代码也可以将其转换为double.

//

// g1FuelCostYear field

//

private double g1FuelCostYear;

@Bindable

public String getG1FuelCostYear() {

NumberFormat nf = NumberFormat.getCurrencyInstance();

return nf.format(this.g1FuelCostYear);

//return Double.valueOf(g1FuelCostYear).toString();

}

private Handler hG1FuelCostYearDelay = null;

public void setG1FuelCostYear(String g1FuelCostYear) {

if (hG1FuelCostYearDelay == null)

{

hG1FuelCostYearDelay = new Handler() {

@Override

public void handleMessage(Message msg) {

notifyPropertyChanged(it.techgest.airetcc2.BR.g1FuelCostYear);

}

};

} else {

hG1FuelCostYearDelay.removeCallbacksAndMessages(null);

}

boolean success = false;

try {

NumberFormat nf = NumberFormat.getCurrencyInstance();

this.g1FuelCostYear = nf.parse(g1FuelCostYear).doubleValue();

success = true;

}

catch (Exception ex) {

this.g1FuelCostYear = 0.0;

log(ex);

}

if (!success) {

try {

this.g1FuelCostYear = Double.parseDouble(g1FuelCostYear);

success = true;

} catch (Exception ex) {

this.g1FuelCostYear = 0.0;

log(ex);

}

}

updateG1FuelConsumption();

hG1FuelCostYearDelay.sendEmptyMessageDelayed(0,2500);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值