我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
当前回答
/**
* Set cursor to end of text in edittext when user clicks Next on Keyboard.
*/
View.OnFocusChangeListener onFocusChangeListener = new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View view, boolean b) {
if (b) {
((EditText) view).setSelection(((EditText) view).getText().length());
}
}
};
mEditFirstName.setOnFocusChangeListener(onFocusChangeListener);
mEditLastName.setOnFocusChangeListener(onFocusChangeListener);
这对我很有用!
其他回答
我认为这可以达到你想要的效果。
Editable etext = mSubjectTextEditor.getText();
Selection.setSelection(etext, etext.length());
类似于@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;
}
});
这个问题已经很老了,但我认为如果你想使用Android上最新发布的DataBinding工具,有这个答案可能会很有用,只需在XML中设置这个:
<data>
<variable name="stringValue" type="String"/>
</data>
...
<EditText
...
android:text="@={stringValue}"
android:selection="@{stringValue.length()}"
...
/>
试试这个:
更新:
科特林:
editText.setSelection(editText.length())//placing cursor at the end of the text
Java:
editText.setSelection(editText.getText().length());
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,这将起作用。我已经测试过了,它对我很有效。