Subhendu
Subhendu

Reputation: 41

Android EditText move cursor without showing default keyboard

I am able to hide the default keyboard by using

setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Selection.setSelection(getText(), length());
            return true;
        }
    });

This doesn't move the cursor to the clicked position. I need to move the cursor to the clicked position.

Upvotes: 0

Views: 599

Answers (1)

Subhendu
Subhendu

Reputation: 41

This one worked by creating a separate class extending EditText.

setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch (event.getAction()) {
                case MotionEvent.ACTION_DOWN:
                    Layout layout = ((EditText) v).getLayout();
                    float x = event.getX() + getScrollX();
                    int offset = layout.getOffsetForHorizontal(0, x);
                    if (offset > 0)
                        if (x > layout.getLineMax(0))
                            setSelection(offset);     
                        else
                            setSelection(offset - 1);
                    break;
            }
            return true;
        }
    });

Upvotes: 1

Related Questions