android onClick和onTouch事件



1 Question
 
I've got a custom view which acts like a button. I want to change the background when user press it, revert the background to original when user moves the finger outside or release it and I also want to handle onClick/onLongClick events. The problem is that onTouch requires me to return true for ACTION_DOWN or it won't send me the ACTION_UP event. But if I return true the onClick listener won't work.


I thought I solved it by returning false in onTouch and registering onClick - it somehow worked, but was kinda against the docs. I've just received a message from an user telling me that he's not able to long-click on the button, so I'm wondering what's wrong here.


Part of the current code:


public boolean onTouch(View v, MotionEvent evt)
{
  switch (evt.getAction())
  {
    case MotionEvent.ACTION_DOWN:
    {
      setSelection(true); // it just change the background
      break;
    }


    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_OUTSIDE:
    {
      setSelection(false); // it just change the background
      break;
    }
  }


  return false;
}


public void onClick(View v)
{
  // some other code here
}


public boolean onLongClick(View view)
  {
    // just showing a Toast here
    return false;
  }




// somewhere else in code
setOnTouchListener(this);
setOnClickListener(this);
setOnLongClickListener(this);
How do I make them work together correctly?


Thanks in advance


    
 
 

-------------------------------------------------------------------------------------------------------------------------------------------------------------------------
 


 

1 Answer 

 

onClick & onLongClick is actually dispatched from View.onTouchEvent.


if you override View.onTouchEvent or set some specific View.OnTouchListener via setOnTouchListener, you must care for that.


so your code should be something like:


public boolean onTouch(View v, MotionEvent evt)
{
  // to dispatch click / long click event,
  // you must pass the event to it's default callback View.onTouchEvent
  boolean defaultResult = v.onTouchEvent(evt);


  switch (evt.getAction())
  {
    case MotionEvent.ACTION_DOWN:
    {
      setSelection(true); // it just change the background
      break;
    }
    case MotionEvent.ACTION_CANCEL:
    case MotionEvent.ACTION_UP:
    case MotionEvent.ACTION_OUTSIDE:
    {
      setSelection(false); // it just change the background
      break;
    }
    default:
      return defaultResult;
  }


  // if you reach here, you have consumed the event
  return true;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值