got ACTION_CANCEL when moving a TextView

254 views Asked by At

The code is as following. I extended a TextView and overrided its onTouchEvent method. I want to move the whole TextView(not the text itself) left and right. The following code sort of works, but it only let me move the TextView about 0.5 centimeters, and than I got a ACTION_CANCEL event. The TextView is 204dp wide. Anyone can give me some clue why this happens? Thank you.

 package com.zhangfuwen.tenkhours;
import android.content.Context;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.Button;
import android.widget.TextView;
import android.util.AttributeSet;



/**
 * Created by dean on 2015/6/20.
 */
public class MyTextView extends TextView {
private int mHistoricalX;
public MyTextView(Context context, AttributeSet attrs) {
    super(context, attrs);
}

@Override
public boolean onTouchEvent(MotionEvent event) {
    float x = event.getX();
    switch (event.getAction()) {
        case MotionEvent.ACTION_DOWN:
            mHistoricalX = (int)x;
            Log.e("haha", "down.");
            return true;
            //break;
            //return super.onTouchEvent(event);
        case MotionEvent.ACTION_MOVE:
            Log.e("haha", "move.");
            float diff = x - mHistoricalX;
            this.setX( this.getX() + diff);
            invalidate();
            return true;
            //super.onTouchEvent(event);
            //return true;
        case MotionEvent.ACTION_UP:
            //TODO:启动定时器,进行倒计时
            //
            Log.e("haha", "up.");
            diff = x - mHistoricalX;
            this.setX( this.getX() + diff);
            return true;
            //break;
        case MotionEvent.ACTION_OUTSIDE:
            Log.e("haha","outside");
            return true;
        case MotionEvent.ACTION_CANCEL:
            Log.e("haha","cancel");
            return false;
        case MotionEvent.ACTION_HOVER_MOVE:
            Log.e("haha","hover move");
            return true;

            //}
            //return super.onTouchEvent(event);
        default:
            Log.e("haha","action is " + Integer.toString(event.getAction()));
            return true;
            //break;


    }
    //return super.onTouchEvent(event);
}

}

1

There are 1 answers

0
DeanSinaean On

Got it fixed. My main activity is a ViewPager which is responsible for swipe action. When I move the TextView inside it, the ViewPager takes possession of the event. To fix it, I overrided the ViewPager as described in this question.