SelectAll on EditText with Two-Way Data Binding

351 Views Asked by At

I have an Activity with a fragment... In this fragment I'm using two-way DataBinging in an EditText. This EditText is binded to a Double property of the object, and because of this, I had to implement an InverseMethod to convert String -> Double and Double -> String...

In my EditText I configured android:selectAllOnFocus="true", and I'm forcing it also on onCreateView method of the fragment: edQtd.selectAll()

The problem is, that when the fragment appears, the EditText has the focus, but the text is not selected, instead, the cursor is before the first number...

I wanted it to show with all the text selected...

Tried to instead of using the inverse method, just concatenate an empty String, but the result was the same...

From what I saw debbuging it, the binding class generated, sets the text after the fragments creation (after I manually called edQtd.selectAll()), removing the selection...

Any ideas how to solve it?

Edit: For now I solved it adding a TextChangedListener to the EditText, where I select all the text only the first time the text is changed:

edQuantidade.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if(selectAllEdQtdText) {
                edQuantidade.selectAll();
                setSelectAllEdQtdText(false);
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }
    });
1

There are 1 best solutions below

6
On

Add following attributes on EditText in Layout.

<EditText
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:selectAllOnFocus="true"
    />

And remove edQtd.selectAll() from code.

Edit

Because none solution works. This will work because this will trigger selectAll after a delay. Add this after setting model in binding.

    new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
            edQtd.selectAll();
        }
    }, 500);