我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
当前回答
有一个名为append for ediitext的函数,它将字符串值追加到当前edittext值,并将光标放在值的末尾。 你可以将字符串值本身作为当前编辑文本值,并调用append();
myedittext.append("current_this_edittext_string");
其他回答
如果你之前调用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()。
类似于@Anh Duy的回答,但对我没用。我还需要光标移动到最后,只有当用户点击编辑文本,仍然能够选择光标的位置之后,这是唯一的代码,已经为我工作
boolean textFocus = false; //define somewhere globally in the class
//in onFinishInflate() or somewhere
editText.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
editText.onTouchEvent(event);
if(!textFocus) {
editText.setSelection(editText.getText().length());
textFocus = true;
}
return true;
}
});
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
textFocus = false;
}
});
科特林:
将光标设置到起始位置:
val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(0)
将光标设置到EditText的末尾:
val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(editText.text.length)
下面的Code是将光标放在第二个字符之后:
val editText = findViewById(R.id.edittext_id) as EditText
editText.setSelection(2)
JAVA:
将光标设置到起始位置:
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(0);
将光标设置到EditText的末尾:
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(editText.getText().length());
下面的Code是将光标放在第二个字符之后:
EditText editText = (EditText)findViewById(R.id.edittext_id);
editText.setSelection(2);
您应该能够在EditText的方法setSelection()的帮助下实现这一点,请参阅这里
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,这将起作用。我已经测试过了,它对我很有效。