我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
当前回答
public class CustomEditText extends EditText {
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditText(Context context) {
super(context);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
this.setSelection(this.getText().length());
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
}
}
在XML文件中使用此CustomEditText,这将起作用。我已经测试过了,它对我很有效。
其他回答
有一个名为append for ediitext的函数,它将字符串值追加到当前edittext值,并将光标放在值的末尾。 你可以将字符串值本身作为当前编辑文本值,并调用append();
myedittext.append("current_this_edittext_string");
试试这个:
更新:
科特林:
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())
}
}
}
如果你想选择所有文本,只是输入新的文本而不是旧的,你可以使用
android:selectAllOnFocus="true"
public class CustomEditText extends EditText {
public CustomEditText(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditText(Context context) {
super(context);
}
public CustomEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(focused, direction, previouslyFocusedRect);
this.setSelection(this.getText().length());
}
@Override
protected void onSelectionChanged(int selStart, int selEnd) {
}
}
在XML文件中使用此CustomEditText,这将起作用。我已经测试过了,它对我很有效。