Skip to content Skip to sidebar Skip to footer

Android: Setting Colors For Relativelayout Inside Ontouchlistener

I am having some relativeLayout, inside which there are multiple textview and imagebuttons, so in order not to making onTouchListener one by one, I have implemented the below code:

Solution 1:

Just return true instead of false.

According to onTouch method doc, the return value is True if the listener has consumed the event, false otherwise. This means that when you return false, successive events will not be passed to your listener.

You can also refer my answer here which has example in comments.

Solution 2:

1st clear previous color first then apply new color and also return true not the false,if you return false then it will listen touch only single time,not multiple times:

 relative1.setOnTouchListener(new OnTouchListener() 
    {
        @Override
        public boolean onTouch(View arg0, MotionEvent event) 
        {
            if(event.getAction()==MotionEvent.ACTION_DOWN )
            {
                relative1.setBackgroundColor(getResources().getColor(R.color.tran_black));
            }

            if((event.getAction()==MotionEvent.ACTION_UP || event.getAction()==MotionEvent.ACTION_CANCEL))
            {   //first clear previous color
                relative1.setBackgroundColor(0);
                //now set new color
                relative1.setBackgroundColor(getResources().getColor(android.R.color.transparent));
            }
            returntrue;
        }           
    }); 

Solution 3:

just return true for onAction down,up and cancel else return super.setOnTouchListener() it will work..because it may effect the other listener for that relative layout

Post a Comment for "Android: Setting Colors For Relativelayout Inside Ontouchlistener"