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


当前回答

使用下面的行

e2.setSelection(e2.length());

e2是编辑文本对象名称

其他回答

让editText2是你的第二个EditText视图。然后将以下代码放在onResume()中

editText2.setFocusableInTouchMode(true);
editText2.requestFocus();

或者把

<requestFocus />

在第二个EditText视图的xml布局中。

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

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

使用下面的行

e2.setSelection(e2.length());

e2是编辑文本对象名称

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

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

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

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