我想为按钮处理三个不同的事件,例如按钮被触摸,按下并释放时。这怎么可能?请帮帮我。
这是我迄今为止开发的用于处理两个事件的代码,但我需要三个事件。
button.setOnTouchListener(new OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
// Check if the button is TOUCH
if (event.getAction() == MotionEvent.ACTION_DOWN)
{
}
// Check if the button is RELEASED
else if (event.getAction() == MotionEvent.ACTION_UP)
{
}
return true;
}
});
答案 0 :(得分:0)
到目前为止,您所开发的内容似乎很好,应该可以正常处理触摸和释放事件。长按有点复杂但没有什么可幻想的。你最好使用GestureDetector
。 this answer中给出了一个例子。或者,您可以参考official documentation。
更新:您可能会发现official tutorial on gestures非常有用。我相信特别是public void onLongPress(MotionEvent event)
方法将满足您的需求!
答案 1 :(得分:-1)
你会试试这个我希望它能适合你的情况...... 您只需使用此活动并使用此方法实现最佳... 你只需使用下面的监听器类来实现长按....
public class MainActivity extends Activity {
private Button button;
int check=0;
private GestureDetector detector;
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
button = (Button)findViewById(R.id.button1);
detector = new GestureDetector(new GestureListener());
check=0;
button.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
detector.onTouchEvent(event);
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_MOVE:
System.out.println("Move");
break;
case MotionEvent.ACTION_DOWN:
System.out.println("Down");
break;
case MotionEvent.ACTION_UP:
System.out.println("Released");
break;
default:
break;
}
return false;
}
});
}
class GestureListener implements OnGestureListener
{
@Override
public boolean onDown(MotionEvent e) {
System.out.println("Down List");
return false;
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
System.out.println("Fly List");
return false;
}
@Override
public void onLongPress(MotionEvent e) {
System.out.println("Long press");
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
return false;
}
@Override
public void onShowPress(MotionEvent e) {
System.out.println("Press List");
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
System.out.println("Single Tap List");
return false;
}
}
}