当edittext的默认文本为浮点值时,Edit text光标将重置为左侧 [英] Edit text cursor resets to left when default text of edittext is a float value
问题描述
我正在使用绑定适配器来防止2方式绑定的edittext不断更新文本.
I am using Binding adapter to prevent constant text update of edittexts for 2 way binding.
@BindingAdapter("binding")
public static void bindEditText(EditText editText, final String str) {
if ((!editText.getText().toString().equals(str)) && !editText.getText().equals("")) {
editText.setText(str);
}
}
对于带有整数默认文本的编辑文本,它可以正常工作.但是,要使用浮动默认文本来编辑文本.例如:70.0,当我键入第一位数字时,编辑文本将刷新并变成例如:8.0.然后,光标向左移动,随后的所有数字将被添加到前面.例如:198.0
It works fine with edit text with integer default text. But when it comes to edit text with float default text. Ex: 70.0, when I key in the first digit, the edit text refreshes and became Ex: 8.0. The cursor then move to left and all the following digits will be added to the front. Ex: 198.0
尝试过此方法,但不起作用.
Tried this, but doesn't work.
@BindingAdapter("binding")
public static void bindEditText(EditText editText, final String str) {
if ((!(editText.getText().toString()+".0").equals(str)) && !editText.getText().equals("")) {
editText.setText(str);
}
}
有解决方案吗?
推荐答案
我不确定所有人都知道:Android数据绑定现在支持双向绑定.您需要Android Studio 2.1,然后可以使用额外的'='字符将字段绑定为双向:
I'm not sure everyone knows: Android Data Binding now supports two-way binding. You need Android Studio 2.1 and then you can bind your field as two-way using an extra '=' character:
<EditText android:text="@={user.name}" .../>
您不需要任何其他的绑定适配器.
You won't need any additional Binding Adapter.
https://halfthought.wordpress .com/2016/03/23/2-way-data-binding-on-android/
也就是说,您正在将浮点数分配给String字段.使用Android Studio 2.2 gradle插件,您将可以使用快捷方式来实现双向转换和原始转换:
That said, you're assigning a float to a String field. With the Android Studio 2.2 gradle plugin, you'll be able to use a shortcut for this that allows two-way binding with primitive conversions:
<EditText android:text="@={`` + data.floatNumber}" .../>
但是,使用Android Studio 2.1时,您必须进行自己的转换,即绑定适配器.这使用户可以编辑字段,并且只接受有效的浮点数:
But with Android Studio 2.1, you'll have to do your own conversions Binding Adapters. This one lets the user edit the field and only accepts a valid float:
@BindingAdapter("android:text")
public static void setText(TextView view, float value) {
boolean setValue = view.getText().length() == 0;
try {
if (!setValue) {
setValue = Float.parseFloat(view.getText().toString()) != value;
}
} catch (NumberFormatException e) {
}
if (setValue) {
view.setText(String.valueOf(value));
}
}
@InverseBindingAdapter(attribute = "android:text")
public static float getText(TextView view) {
try {
return Float.parseFloat(view.getText().toString());
} catch (NumberFormatException e) {
return 0;
}
}
这篇关于当edittext的默认文本为浮点值时,Edit text光标将重置为左侧的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!