Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android EditText: How to disable cursor move on touch?

I have EditText which displays something like ###-###. I want the user to be able to change this text only from the 1st position onward. That is user should not be able to touch a # in the middle and change it. How can I do this? Thanks a lot.

Sorry, I was not precise in my question. I want to disable even tapping in the middle of the text.

like image 364
Alexander Kulyakhtin Avatar asked Oct 16 '11 19:10

Alexander Kulyakhtin


People also ask

How do I remove the cursor from Edit text?

To hide the cursor we implement this method for each Edit Text: “setCursorVisible(false)”


3 Answers

This will receive the on click event when the edit text doesn't have focus. so The user can click on the edit text to transfer the focus, and on focus change listener will update the cursor position to end.

cardNumberEditText.setOnTouchListener { v, event ->
        return@setOnTouchListener cardNumberEditText.hasFocus()

    }
    cardNumberEditText.setOnFocusChangeListener { v, hasFocus ->
        if (hasFocus) {
            cardNumberEditText.setSelection(
                cardNumberEditText.text.length
            )
        }
    }
like image 194
Awais Abbas Avatar answered Oct 04 '22 00:10

Awais Abbas


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());
    }
}
like image 21
MikeIsrael Avatar answered Oct 04 '22 01:10

MikeIsrael


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.

like image 35
Terel Avatar answered Oct 04 '22 02:10

Terel