我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
当前回答
你也可以像这样把光标放在EditText视图中文本的末尾:
EditText et = (EditText)findViewById(R.id.textview);
int textLength = et.getText().length();
et.setSelection(textLength, textLength);
其他回答
这是另一种可能的解决方案:
et.append("");
如果因为某种原因不管用,试试下面的方法:
et.setSelection(et.getText().length());
您应该能够在EditText的方法setSelection()的帮助下实现这一点,请参阅这里
试试这个:
更新:
科特林:
editText.setSelection(editText.length())//placing cursor at the end of the text
Java:
editText.setSelection(editText.getText().length());
完全工作的解决方案!!
kotlin,你需要用post
fun EditText.placeCursorToEnd() {
this.setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
v.post { this.setSelection(text.length) }
}
}
this.setOnClickListener {
it.post { this.setSelection(text.length) }
}
}
editText.setOnKeyListener(new View.OnKeyListener() {
@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
editText.setSelection(editText.getText().length());
return false;
}
});