我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
我正在更改keyListener上的EditText的值。
但是当我更改文本时,光标移动到EditText的开头。 我需要光标在文本的末尾。
如何将光标移动到EditText文本的末尾。
当前回答
试试这个:
<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
其他回答
有一个名为append for ediitext的函数,它将字符串值追加到当前edittext值,并将光标放在值的末尾。 你可以将字符串值本身作为当前编辑文本值,并调用append();
myedittext.append("current_this_edittext_string");
如果您想将光标放置在EditText视图中文本的末尾
EditText rename;
String title = "title_goes_here";
int counts = (int) title.length();
rename.setSelection(counts);
rename.setText(title);
上面的答案对我没用。所以我找到了一个新的解决方案。这可能对某些人有帮助。我一直在使用最新版本的Android Studio,即目前为止的3.5。也许这就是以上答案没有显示出任何效果的原因。
代码:
EditText available_seats = findViewById(R.id.available_seats);
Selection.setSelection(available_seats.getText(),available_seats.getText().length());
这里,第一个参数是你想要使用的Spannable文本值,而第二个参数是索引值。因为我们希望光标位于文本的末尾,所以我们使用getText().length()来返回文本的长度
在我的情况下,我创建了以下Kotlin ext.函数,可能对某人有用:
private fun EditText.focus(){
requestFocus()
setSelection(length())
}
然后按如下方式使用:
mEditText.focus()
完全工作的解决方案!!
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) }
}
}