Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EditText, OnTouchListener and setSelection doesn't work on first touch

I've got the following code which fires every time my "redTime" EditText is touched.

redTime.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Log.i("click", "onMtouch");
            redTime.setSelection(redTime.getText().length());
            return false;
        }
    });

It is meant to keep the cursor on the right side of the EditText upon every touch. The problem is that the line containing the "setSelection" method doesn't work upon the FIRST touch of the control. That is, if another control has focus, and I touch the "redTime" control for the first time, the method is fired, but the cursor remains at the location I touched (not the right side).

How do I know the listener fires? The "Log.i" call works, but not the cursor change. I suspect the "setSelection" call is working, but some later event is negating it.

I tried a few things. I tried consuming the event by returning TRUE in the listener. Didn't work. I tried repeating the "setSelection" call in OnTouchListener, and OnFocusChanged as well. Still doesn't work.

I almost forgot. Here is the XML for the control in question.

<EditText
            android:id="@+id/redEditText"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:ellipsize="end"
            android:gravity="right"
            android:inputType="time"
            android:text="@string/zeroTime"
            android:textColor="#ff0000"
            android:textSize="32sp" >
        </EditText>
like image 391
mcsilvio Avatar asked Jan 27 '26 05:01

mcsilvio


1 Answers

I ran into this issue recently and couldn't get anything to work, so ended up doing this:

    setOnTouchListener(new OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            postDelayed(new Runnable() {
                @Override
                public void run() {
                    setSelection(getText().length());
                }
            }, 50);
            return false;
        }
    });