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

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

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


当前回答

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,这将起作用。我已经测试过了,它对我很有效。

其他回答

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

et.append("");

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

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

editText。这里的setSelection很神奇。基本上选择让你把光标放在任何你想要的位置。

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

这将光标放置到EditText的末尾。基本上,editText.getText().length()会给出文本长度。然后使用setSelection with length。

editText.setSelection(0);

它用于将光标设置在起始位置(0)。

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

代码:

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

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

完全工作的解决方案!!

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) }
    }
}

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

    android:selectAllOnFocus="true"