我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改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()。
其他回答
在我的情况下,我创建了以下Kotlin ext.函数,可能对某人有用:
private fun EditText.focus(){
requestFocus()
setSelection(length())
}
然后按如下方式使用:
mEditText.focus()
我认为这可以达到你想要的效果。
Editable etext = mSubjectTextEditor.getText();
Selection.setSelection(etext, etext.length());
如果您想将光标放置在EditText视图中文本的末尾
EditText rename;
String title = "title_goes_here";
int counts = (int) title.length();
rename.setSelection(counts);
rename.setText(title);
这是另一种可能的解决方案:
et.append("");
如果因为某种原因不管用,试试下面的方法:
et.setSelection(et.getText().length());
您应该能够在EditText的方法setSelection()的帮助下实现这一点,请参阅这里