Android: setting colors for relativelayout inside onTouchListener

无人久伴 提交于 2019-12-11 08:38:27

问题


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:

    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))
            {
                relative1.setBackgroundColor(getResources().getColor(android.R.color.transparent));
            }
            return false;
        }           
    }); 

Question:

The relative1 RelativeLayout has turned to tran_black color when pressed, but it fails to turn back to transparent upon Action_up.

How could that be ameneded? Thanks!


回答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.




回答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));
            }
            return true;
        }           
    }); 



回答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



来源:https://stackoverflow.com/questions/20787733/android-setting-colors-for-relativelayout-inside-ontouchlistener

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!