EditText,如何在TextWatcher中控制光标?

Jos*_*tro 3 android cursor textwatcher android-edittext

我在EditText上有一个TextWatcher,在afterTextChanged方法中,我将字符添加到EditText然后我将光标移动到EditText的末尾以继续添加文本,但我遇到了问题.

像这样:

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());
      }
}
Run Code Online (Sandbox Code Playgroud)

在android 4.0v或更高版本中,光标停留在"."之前.,并在2.2v工作正常,但在我都无法删除字符.

谁有同样的问题?

素不相识

Aru*_*n C 5

您可以这样做以避免删除问题...

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();
            }
        });
    }
Run Code Online (Sandbox Code Playgroud)