Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText, How can control the cursor in TextWatcher?

I have a TextWatcher on an EditText, in the method afterTextChanged, I add characters to the EditText then I move the cursor to the end of EditText for continue adding text, but I have problems with that.

Like this:

public void afterTextChanged(Editable s) {

    if(edittext.getText().length()==2){

        // append dot to edittext
        edittext.append(".");
        // move cursor at end position in EditText
        edittext.setSelection(edittext.getText().length());
      }
}

In android 4.0v or superior, the cursor stay before the "." , and In 2.2v works fine, but in both I can't delete the characters.

Anyone with the same problem ?

Grettings

like image 708
José Castro Avatar asked Jan 13 '23 09:01

José Castro


2 Answers

You can do something like this to avoid delete problem...

public class MainActivity extends Activity {
    int count=0;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        final EditText edittext=(EditText)findViewById(R.id.editText1);

        edittext.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable ed) {
                // TODO Auto-generated method stub

                 if(edittext.getText().length()==2 && count < 3){

                        // append dot to edittext
                        edittext.append(".");
                        // move cursor at end position in EditText
                        edittext.setSelection(edittext.getText().length());
                      }
                 count=edittext.getText().length();
            }
        });
    }
like image 59
Arun C Avatar answered Jan 18 '23 14:01

Arun C


Your code looks fine...

But, if you delete a character, text length is == 2 again and your code will automatically add a '.' char again - so it looks like deleting is not possible.

like image 31
Jörn Buitink Avatar answered Jan 18 '23 12:01

Jörn Buitink