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


当前回答

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

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

其他回答

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

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

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

其中position为int型:

editText1.setSelection(position)

这将把光标移动到edittext的末尾

.toString myEditText.setSelection (myEditText.getText () () . length ())

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

if(myEditText.isSelected){
    myEditText.setSelection(myEditText.length())
    }