我在keyListener
上更改了一个EditText
的值。
但是当我更改文本时,光标会移动到EditText
的开头。
我需要光标在文本末尾。
如何将光标移动到EditText
的末尾。
我在keyListener
上更改了一个EditText
的值。
但是当我更改文本时,光标会移动到EditText
的开头。
我需要光标在文本末尾。
如何将光标移动到EditText
的末尾。
etSSID.setSelection(etSSID.getText().length());
editText.setText("");
if (!TextUtils.isEmpty(text)) {
editText.append(text);
}
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;
}
});
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,这将起作用。我已经测试过了,对我来说是可行的。
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())
}
}
}
如果你想在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(),它返回文本的长度。
fun EditText.setCursorToEnd() {
setOnFocusChangeListener { v, hasFocus ->
if (hasFocus) {
showKeyboard(this) // call your show keyboard function
val text = this.text.toString()
this.setText(text)
this.setSelection(text.length) // Move the cursor to the end
}
}
}
ListView
中作为项目的EditText
的问题。至于实验,我对ListView
源代码进行了一些更改,这是一个相当复杂的东西,并在模拟器上进行了测试。它与组件所做的焦点控制管理有关。所以当然,这不是我可以给我们的朋友帮助的解决方案。 :) - kanedaOnFocusChanged
回调中不起作用。解决方法是将setSelection
放入一个可运行的对象中,并在主线程上运行它。请参考此处 https://dev59.com/e4rda4cB1Zd3GeqPHxcg#32156989 - Ali Nem