Place cursor at the end of text in EditText

2019-01-05 06:34发布

I am changing the value of an EditText on keyListener.

But when I change the text the cursor is moving to the beginning of the EditText. I need the cursor to be at the end of the text.

How to move the cursor to the end of the text in a EditText.

23条回答
一纸荒年 Trace。
2楼-- · 2019-01-05 07:14
/**
 * Set cursor to end of text in edittext when user clicks Next on Keyboard.
 */
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
    @Override
    public void onFocusChange(View view, boolean b) {
        if (b) {
            ((EditText) view).setSelection(((EditText) view).getText().length());
        }
    }
};

mEditFirstName.setOnFocusChangeListener(onFocusChangeListener); 
mEditLastName.setOnFocusChangeListener(onFocusChangeListener);

It work good for me!

查看更多
干净又极端
3楼-- · 2019-01-05 07:19

Kotlin:

set the cursor to the starting position:

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(0)

set the cursor to the end of the EditText:

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(editText.getText().length())

Below Code is to place the cursor after the second character:

val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(2)

JAVA:

set the cursor to the starting position:

 EditText editText = (EditText)findViewById(R.id.edittext_id);
 editText.setSelection(0);

set the cursor to the end of the EditText:

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(editText.getText().length());

Below Code is to place the cursor after the second character:

EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(2);
查看更多
男人必须洒脱
4楼-- · 2019-01-05 07:19

You should be able to achieve that with the EditText's method setSelection(), see here

查看更多
来,给爷笑一个
5楼-- · 2019-01-05 07:20

If you called setText before and the new text didn't get layout phase call setSelection in a separate runnable fired by View.post(Runnable) (repost from this topic).

So, for me this code works:

editText.setText("text");
editText.post(new Runnable() {
         @Override
         public void run() {
             registerPhone.setSelection("text".length());
         }
});
查看更多
三岁会撩人
6楼-- · 2019-01-05 07:20

You could also place the cursor at the end of the text in the EditText view like this:

EditText et = (EditText)findViewById(R.id.textview);
int textLength = et.getText().length();
et.setSelection(textLength, textLength);
查看更多
\"骚年 ilove
7楼-- · 2019-01-05 07:20

If your EditText is not clear:

editText.setText("");
editText.append("New text");
查看更多
登录 后发表回答