Two-Way databinding in EditText

后端 未结 6 856
无人共我
无人共我 2020-12-15 06:20

I have this object

ObservableInt someNumber;

public ObservableInt getSomeNumber()
{
    return someNumber;
}

public void setSomeNumber(ObservableInt numbe         


        
6条回答
  •  借酒劲吻你
    2020-12-15 06:56

    Thanks to the binding adapters from @LongRanger I was able to advance a lot more in my solution but I had to make some changes on the adapters and in my code. First of all I had to init the ObservableInt member like this:

    ObservableInt someNumber;
    
    public ObservableInt getSomeNumber()
    {
        return someNumber;
    }
    
    public void setSomeNumber(ObservableInt number)
    {
        this.someNumber = number;
    }
    

    Second, I had to change the adapters given by @LongRanger to be like this:

    @BindingAdapter("android:text")
    public static void bindIntegerInText(AppCompatEditText tv, int value)
    {
        tv.setText(String.valueOf(value));    
    
        // Set the cursor to the end of the text
        tv.setSelection(tv.getText().length());
    }
    
    @InverseBindingAdapter(attribute = "android:text")
    public static int getIntegerFromBinding(TextView view)
    {
        String string = view.getText().toString();
    
        return string.isEmpty() ? 0 : Integer.parseInt(string);
    }
    

    That way I avoid the error: Invalid int "", when trying to do Integer.parse(...) on the @InverseBindingAdapter. After this I had to put the cursor on the end of the EditText with the @BindingAdapter, otherwise the cursor kept moving to the start.

提交回复
热议问题