有两个EditText,在加载页面时,在第一个EditText中设置了一个文本,所以现在光标将位于EditText的起始位置,我想在第二个EditText中设置光标的位置,其中不包含数据。如何做到这一点?


当前回答

Edittext中的setSelection(int index)方法应该允许您这样做。

其他回答

Edittext中的setSelection(int index)方法应该允许您这样做。

我相信最简单的方法就是使用填充。

Say in your xml's edittext section, add android: paddingLeft = " 100 dp” This will move your start position of cursor 100dp right from left end.

同理,你可以用 android: paddingRight = " 100 dp” 这将把你的光标的结束位置从右端向左移动100dp。

要了解更多细节,请查看我博客上的这篇文章:Android:在EditText Widget中设置光标的起始和结束位置

在kotlin中,你可以像这样创建一个扩展函数:

fun EditText.placeCursorAtLast() {
    val string = this.text.toString()
    this.setSelection(string.length)
}

然后简单地调用myEditText.placeCursorAtLast()

记住在setSelection之前调用requestFocus()用于edittext。

我用这种方法在以编程方式更新EditText文本后,将光标位置设置为文本的末尾 这里,etmsg是EditText

etmsg.setText("Updated Text From another Activity");
int position = etmsg.length();
Editable etext = etmsg.getText();
Selection.setSelection(etext, position);