Android ACTION_UP does not get fired after ACTION_

2019-08-08 13:25发布

问题:

I'm trying to create a view programmatically, and change its background according to its click state.

I know I can do this with xml drawables, but I want to learn to program it too.

But if I press on my view, then slide my finger, the view gets stuck in pressed state. (white = 0xaaffffff background)

My code is this :

Edit:

I solved the problem. Here is the working code :

mainContainer.setOnTouchListener(new OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {             
            // TODO Auto-generated method stub

            int action = event.getAction();
            if (action==MotionEvent.ACTION_DOWN)
            {
                v.setBackgroundColor(0xaaffffff);                   
                return false;
            }               

            if(action==MotionEvent.ACTION_MOVE)
            {                   

            }

            if(action==MotionEvent.ACTION_CANCEL)
            {                  
                v.setBackgroundColor(0x00ffffff);
            }

            if (action==MotionEvent.ACTION_UP)
            {               
                v.setBackgroundColor(0x00ffffff);                   
                return true;
            }


            return false;

        }
    });

As you see, I tried returning true wherever I want onTouch() to be called again. But apparently there is something I do not understand here.

What am I doing wrong ?

Thanks for any help.

回答1:

What about returning true in your ACTION_UP aswell?

if (action==MotionEvent.ACTION_UP)

    {               
      v.setBackgroundColor(0x00ffffff);
      return true;
    }