我正在更改keyListener上的EditText的值。

但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。

如何将光标移动到EditText文本的末尾。


当前回答

类似于@Anh Duy的回答,但对我没用。我还需要光标移动到最后,只有当用户点击编辑文本,仍然能够选择光标的位置之后,这是唯一的代码,已经为我工作

boolean textFocus = false; //define somewhere globally in the class

//in onFinishInflate() or somewhere
editText.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {

        editText.onTouchEvent(event);

        if(!textFocus) {
            editText.setSelection(editText.getText().length());
            textFocus = true;
        }

        return true;
    }
});

editText.setOnFocusChangeListener(new OnFocusChangeListener() {
    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        textFocus = false;
    }
});

其他回答

在我的情况下,我创建了以下Kotlin ext.函数,可能对某人有用:

private fun EditText.focus(){
    requestFocus()
    setSelection(length())
}

然后按如下方式使用:

mEditText.focus()

您应该能够在EditText的方法setSelection()的帮助下实现这一点,请参阅这里

这个问题已经很老了,但我认为如果你想使用Android上最新发布的DataBinding工具,有这个答案可能会很有用,只需在XML中设置这个:

<data>
    <variable name="stringValue" type="String"/>
</data>
...
<EditText
        ...
        android:text="@={stringValue}"
        android:selection="@{stringValue.length()}"
        ...
/>

试试这个:

更新:

科特林:

editText.setSelection(editText.length())//placing cursor at the end of the text

Java:

editText.setSelection(editText.getText().length());

这是

Editable etext = edittext.getText();
Selection.setSelection(etext,edittext.getText().toString().length());