[英]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: 我有一些relativeLayout,其中有多个textview和imagebutton,所以为了不使onTouchListener
一对一,我实现了以下代码:
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;
}
});
The relative1
RelativeLayout
has turned to tran_black
color when pressed, but it fails to turn back to transparent upon Action_up
. 该relative1
RelativeLayout
已经转向tran_black
按下时的颜色,但它不能在回头透明Action_up
。
How could that be ameneded? 怎么可以修改呢? Thanks! 谢谢!
Just return true
instead of false
. 只需返回true
而不是false
。
According to onTouch method doc , the return value is True if the listener has consumed the event, false otherwise.
根据onTouch方法doc , True if the listener has consumed the event, false otherwise.
则返回值为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. 这意味着当您返回false时,后续事件将不会传递给您的侦听器。
You can also refer my answer here which has example in comments. 您也可以在此处引用我的答案,该答案在示例中带有示例。
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: 第一种是先清除以前的颜色,然后再应用新的颜色,并且还返回true而不是false,如果返回false,则它只会监听一次而不是多次监听:
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;
}
});
只需为onAction向下返回true,向上并取消,否则返回super.setOnTouchListener()
它将起作用..因为它可能影响该相对布局的其他侦听器
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.