Luthervd
Luthervd

Reputation: 1406

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.

Upvotes: 9

Views: 11612

Answers (2)

Sergei Bubenshchikov
Sergei Bubenshchikov

Reputation: 5371

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

Upvotes: 14

Karthik Sridharan
Karthik Sridharan

Reputation: 541

try like this

<EditText
            android:layout_width="100dp"
            android:layout_height="50dp"
            android:inputType="numberDecimal"
            android:text="@={String.valueOf(weightSet.roundInEditAmount)}"/>

Upvotes: 17

Related Questions