How to disable cursor positioning and text selecti

2019-01-17 20:24发布

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.

4条回答
放荡不羁爱自由
2楼-- · 2019-01-17 20:32

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楼-- · 2019-01-17 20:38

Try this:

mEditText.setMovementMethod(null);
查看更多
倾城 Initia
4楼-- · 2019-01-17 20:40

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);
    }

}
查看更多
姐就是有狂的资本
5楼-- · 2019-01-17 20:52

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. */

}
查看更多
登录 后发表回答