Search code examples
androidevent-handlingtouchonclicklistenerandroid-event

How to detect if click event is finished in android?


I create views dynamically, and I handle their click events normally, like this :

myView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                v.setBackgroundColor(0xaaffffff);


            }
        });

But this code does not handle the onRelease event, so the view remains with white background, after the click.

So how can I set the background to another value when the clicked state is over ?

Thanks in advance !

Edit:

OnTouchListener does the exact same thing. I guess I need something like onReleaseListener ?


Solution

  • For that you need to use an onTouchListener => documentation

    Refer this tutorial on how to use this.

    Example:

    myView.setOnTouchListener(
            new View.OnTouchListener() {
            public boolean onTouch(View myView, MotionEvent event) {
                int action = event.getAction();
                if (action==MotionEvent.ACTION_MOVE)
                {
                    myView.setBackgroundColor(Color.BLUE);
                }
                if (action==MotionEvent.ACTION_UP)
                {
                    myView.setBackgroundColor(Color.RED);
                }
                if (action==MotionEvent.ACTION_DOWN)
                {
                    myView.setBackgroundColor(Color.YELLOW);
                }
                // TODO Auto-generated method stub
                return true;
            }
        }