Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android DataBinding float to TextView

I am trying to bind:

 @Bindable
public float getRoundInEditAmount()
{
    return roundInEdit.getAmount();
}

@Bindable
public void setRoundInEditAmount(float amount)
{
    roundInEdit.setAmount(amount);
    notifyPropertyChanged(BR.roundInEditAmount);
}

to

 <EditText
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:inputType="numberDecimal"
            android:text="@={`` + weightSet.roundInEditAmount}"
            ></EditText>

However on clicking the EditText I am presented with a a text input not the number pad. If I click this EditText again I am then presented with the number pad. If the field has been defaulted to 50.0 or another value I cannot delete these amounts. I can enter text though and it does persist.

Has anyone else come across this behavior with the text input coming up on first click rather than the number pad? Also does the two way binding on EditText work the way I am expecting. I have written my own Binding and InverseBinding adapter and they behave in the same way -> TextInput on first click and then number pad on second click but you cant delete the number that you start with.

like image 503
Luthervd Avatar asked Dec 15 '16 00:12

Luthervd


2 Answers

try like this

<EditText
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:inputType="numberDecimal"
            android:text="@={String.valueOf(weightSet.roundInEditAmount)}"/>
like image 72
Karthik Sridharan Avatar answered Nov 02 '22 22:11

Karthik Sridharan


If you use Android Databinding Library, it solves by creating binding adapter.

public class BindingUtils {

    @BindingAdapter("android:text")
    public static void setFloat(TextView view, float value) {
        if (Float.isNaN(value)) view.setText("");
        else view.setText( ... you custom formatting );
    }

    @InverseBindingAdapter(attribute = "android:text")
    public static float getFloat(TextView view) {
        String num = view.getText().toString();
        if(num.isEmpty()) return 0.0F;
        try {
           return Float.parseFloat(num);
        } catch (NumberFormatException e) {
           return 0.0F;
        }
    }
}
like image 14
Sergey Bubenshchikov Avatar answered Nov 02 '22 22:11

Sergey Bubenshchikov