Edit text cursor resets to left when default text

2019-07-14 07:26发布

问题:

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

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

Any solution?

回答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/

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}" .../>

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