问题
I'm searching for a way to prevent the user from moving the cursor position anywhere. The cursor should always stay at the end of the current EditText value. In addition to that the user should not be able to select anything in the EditText. Do you have any idea how to realize that in Android using an EditText?
To clarify: the user should be able to insert text, but only at the end.
回答1:
I had the same problem. This ended up working for me:
public class CustomEditText extends EditText {
@Override
public void onSelectionChanged(int start, int end) {
CharSequence text = getText();
if (text != null) {
if (start != text.length() || end != text.length()) {
setSelection(text.length(), text.length());
return;
}
}
super.onSelectionChanged(start, end);
}
}
回答2:
This will reset cursor focus to the last position of the text
editText.setSelection(editText.getText().length());
This method will disable cursor move on touch
public class MyEditText extends EditText{
@Override
public boolean onTouchEvent(MotionEvent event)
{
final int eventX = event.getX();
final int eventY = event.getY();
if( (eventX,eventY) is in the middle of your editText)
{
return false;
}
return true;
}
}
And You can use either the xml attribute
android:cursorVisible
or the java function
setCursorVisible(boolean)
to disable blinking cursor of edittext
回答3:
Try this:
mEditText.setMovementMethod(null);
回答4:
It sounds like the best way to do this is to make your own CustomEditText
class and override/modify any relevant methods. You can see the source code for EditText
here.
public class CustomEditText extends EditText {
@Override
public void selectAll() {
// Do nothing
}
/* override other methods, etc. */
}
来源:https://stackoverflow.com/questions/11170409/how-to-disable-cursor-positioning-and-text-selection-in-an-edittext-android