我正在更改keyListener上的EditText的值。

但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。

如何将光标移动到EditText文本的末尾。


当前回答

上面的答案对我没用。所以我找到了一个新的解决方案。这可能对某些人有帮助。我一直在使用最新版本的Android Studio,即目前为止的3.5。也许这就是以上答案没有显示出任何效果的原因。

代码:

EditText available_seats = findViewById(R.id.available_seats);
Selection.setSelection(available_seats.getText(),available_seats.getText().length());

这里,第一个参数是你想要使用的Spannable文本值,而第二个参数是索引值。因为我们希望光标位于文本的末尾,所以我们使用getText().length()来返回文本的长度

其他回答

你也可以像这样把光标放在EditText视图中文本的末尾:

EditText et = (EditText)findViewById(R.id.textview);
int textLength = et.getText().length();
et.setSelection(textLength, textLength);
/**
 * 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);

这对我很有用!

试试这个:

<EditText
    android:id="@+id/edt_text"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="Hello World!"
    android:cursorVisible="true"/>

在你的代码中:

EditText editText = findViewById(R.id.editText);
editText.setSelection(editText.getText().length()); // Set cursor end point

我认为这可以达到你想要的效果。

 Editable etext = mSubjectTextEditor.getText();
 Selection.setSelection(etext, etext.length());

有一个名为append for ediitext的函数,它将字符串值追加到当前edittext值,并将光标放在值的末尾。 你可以将字符串值本身作为当前编辑文本值,并调用append();

myedittext.append("current_this_edittext_string");