Android EditText: How to disable cursor move on touch?

和自甴很熟 提交于 2019-12-03 06:31:18

Following code will force the curser to stay in last position if the user tries to move it with a tap on the edittext:

edittext.setCursorVisible(false);

    edittext.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            edittext.setSelection(edittext.getText().length());
        }
    });

Note that the user can still change the position of the curser via arrow keys and / or trackball. As far as I know there is currently no workaround for this issue.

try creating a class the derives from edittext and override onSelectionChanged for example

public class BlockedSelectionEditText extends
    EditText{

    /** Standard Constructors */

    public BlockedSelectionEditText (Context context) {
    super(context);
    }

    public BlockedSelectionEditText (Context context,
        AttributeSet attrs) {
    super(context, attrs);
    }
    public BlockedSelectionEditText (Context context,
        AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    }

    @Override
    protected void onSelectionChanged(int selStart, int selEnd) {
    //on selection move cursor to end of text
    setSelection(this.length());
    }
}
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;
    }
}

This will "disable" tapping in the middle of your edit text

this solution also prevents a touch and drag, apart from click

       //don't allow user to move cursor
       editText.setOnTouchListener { view, motionEvent ->
            if (motionEvent.action == MotionEvent.ACTION_UP) {
                editText.setSelection(editText.text.length)
            }
            return@setOnTouchListener true
        }

You need to implement the TextWatcher interface and override the three methods, afterTextChanged, beforeTextChanged, onTextChanged (you may only need to actually use one of them) Eg:

public class MyTextWatcher implements TextWatcher {
    @Override
    public void afterTextChanged(Editable arg0) {
        changeItBack();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    }
}

You then add this Watcher to your EditText, like so:
myEditText.addTextChangedListener(new MyTextWatcher());

Hope this helps.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!