我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
当前回答
在我的情况下,我创建了以下Kotlin ext.函数,可能对某人有用:
private fun EditText.focus(){
requestFocus()
setSelection(length())
}
然后按如下方式使用:
mEditText.focus()
其他回答
这是另一种可能的解决方案:
et.append("");
如果因为某种原因不管用,试试下面的方法:
et.setSelection(et.getText().length());
试试这个:
更新:
科特林:
editText.setSelection(editText.length())//placing cursor at the end of the text
Java:
editText.setSelection(editText.getText().length());
editText.accessibilityDelegate = object : View.AccessibilityDelegate() {
override fun sendAccessibilityEvent(host: View?, eventType: Int) {
super.sendAccessibilityEvent(host, eventType)
if (eventType == TYPE_VIEW_TEXT_SELECTION_CHANGED) {
editText.setSelection(editText.length())
}
}
}
这个方法很安全:
editText.setText("");
if (!TextUtils.isEmpty(text)) {
editText.append(text);
}
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
editText.setSelection(editText.getText().length());
return false;
}
});