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

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

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


当前回答

完全工作的解决方案!!

kotlin,你需要用post

fun EditText.placeCursorToEnd() {
    this.setOnFocusChangeListener { v, hasFocus ->
        if (hasFocus) {
            v.post { this.setSelection(text.length) }
        }
    }
    this.setOnClickListener {
        it.post { this.setSelection(text.length) }
    }
}

其他回答

public class CustomEditText extends EditText {
    public CustomEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public CustomEditText(Context context) {
        super(context);
    }

    public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }


    @Override
    protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
        super.onFocusChanged(focused, direction, previouslyFocusedRect);
        this.setSelection(this.getText().length());
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {

    }
}

在XML文件中使用此CustomEditText,这将起作用。我已经测试过了,它对我很有效。

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

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

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

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

然后按如下方式使用:

mEditText.focus()

这个方法很安全:

    editText.setText("");
    if (!TextUtils.isEmpty(text)) {
        editText.append(text);
    }

这是另一种可能的解决方案:

et.append("");

如果因为某种原因不管用,试试下面的方法:

et.setSelection(et.getText().length());