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

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

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


当前回答

如果你之前调用setText并且新的文本没有得到布局阶段调用setSelection在一个单独的runnable中由View.post(runnable)触发(从本主题重新发布)。

所以,对我来说,这段代码是有效的:

editText.setText("text");
editText.post(new Runnable() {
         @Override
         public void run() {
             editText.setSelection(editText.getText().length());
         }
});

编辑05/16/2019:现在我正在使用Kotlin扩展:

fun EditText.placeCursorToEnd() {
    this.setSelection(this.text.length)
}

然后- editText.placeCursorToEnd()。

其他回答

如果你想选择所有文本,只是输入新的文本而不是旧的,你可以使用

    android:selectAllOnFocus="true"

如果您想将光标放置在EditText视图中文本的末尾

 EditText rename;
 String title = "title_goes_here";
 int counts = (int) title.length();
 rename.setSelection(counts);
 rename.setText(title);

上面的答案对我没用。所以我找到了一个新的解决方案。这可能对某些人有帮助。我一直在使用最新版本的Android Studio,即目前为止的3.5。也许这就是以上答案没有显示出任何效果的原因。

代码:

EditText available_seats = findViewById(R.id.available_seats);
Selection.setSelection(available_seats.getText(),available_seats.getText().length());

这里,第一个参数是你想要使用的Spannable文本值,而第二个参数是索引值。因为我们希望光标位于文本的末尾,所以我们使用getText().length()来返回文本的长度

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

<data>
    <variable name="stringValue" type="String"/>
</data>
...
<EditText
        ...
        android:text="@={stringValue}"
        android:selection="@{stringValue.length()}"
        ...
/>
editText.accessibilityDelegate = object : View.AccessibilityDelegate() {
    override fun sendAccessibilityEvent(host: View?, eventType: Int) {
        super.sendAccessibilityEvent(host, eventType)
        if (eventType == TYPE_VIEW_TEXT_SELECTION_CHANGED) {
            editText.setSelection(editText.length())
        }
    }
}