我遇到的问题是我正在使用onTouch事件的触摸监听器,当我只触摸一次时,似乎不止一次调用触摸。 以下是我的代码
final TextView tv = (TextView)findViewById(R.id.TextView01);
tv.setOnTouchListener(new View.OnTouchListener() {
int count1 =0;
int count2=0;
public boolean onTouch(View arg0, MotionEvent event) {
Log.d("Code777","Touch is being called finger");
int i = event.getPointerCount();
if(i==1 )
{
if(count1==0)
{
Log.d("Code777","Touched with 1 finger");
count1++;
count2=0;
}
}
if (i==2 )
{
if(count2==0)
{
Log.d("Code777","Touched with 2 fingers");
edit.append(tv.getText());
count2++;
count1=0;
}
}
return true;
}
});
我做错了什么? 单次触摸和双触摸打印日志的次数超过3-4次
问题更新的问题是这两个事件现在都被解雇了
if(event.getAction() == MotionEvent.ACTION_POINTER_2_DOWN)
{
Log.d("Code777","2 finger touch");
return true;
}else if(event.getAction() == MotionEvent.ACTION_DOWN)
{
Log.d("Code777","Touched with 1 finger");
return true;
}
答案 0 :(得分:7)
您的代码将在每次触摸事件期间执行。第一次激活时,可能会发生ACITON_DOWN
事件(当用户第一次触摸屏幕时)。第二次,可能会发生ACTION_UP
事件(当用户从屏幕上抬起手指时)。同样,如果您要在屏幕上滑动手指,则ACTION_MOVE
事件将执行相同的代码多次。你必须检查它的触摸类型。做这样的事情:
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
// Do something that should only happen when the user first touches the screen
break;
case MotionEvent.ACTION_MOVE:
// Do something that should only happen when the user is touching the screen
break;
case MotionEvent.ACTION_UP:
// Do something that should only happen when the user stops touching the screen
break;
}
编辑:
Android中的多点触控充其量只是奇数。并非所有设备都可以处理它。并非所有设备都能处理超过x次触摸等。如果您想处理单个手指的DOWN情况,则可以使用ACTION_POINTER_X
项目。如果你有这样一系列的事件,那么:
1. User touches screen
2. User touches screen with second finger
3. User lifts finger 1
4. User touches screen with finger 1
5. User lifts finger 2
6. User touches screen with finger 2
7. User lifts both finger 1 and finger 2
8. User touches screen with only finger 2
9. User touches screen with finger 1
将被解雇的事件将是这样的:
1. ACTION_DOWN
2. ACTION_POINTER_2_DOWN
3. ACTION_POINTER_1_UP
4. ACTION_POINTER_1_DOWN
5. ACTION_POINTER_2_UP
6. ACTION_POINTER_2_DOWN
7. ACTION_UP (also, one of the pointers actions will fire depending on which finger was lifted first)
8. ACTION_DOWN
9. ACTION_POINTER_2_DOWN
等等。
答案 1 :(得分:1)
onTouchListener
通过MotionEvents
向您发送多项操作。您可以使用MotionEvent.getAction()
获取当前事件的操作。
您在此处注意到的最有可能的是,当您移动时,您会得到一个ACTION_DOWN
(手指放在显示屏上)事件,然后是一些小ACTION_MOVE
个事件手指稍微。最后,您将获得ACTION_UP
(手指已被抬起)您可以通过忽略错误操作的事件来过滤掉这些内容。
例如,当发生移动事件时,从onTouch()返回。
public boolean onTouch(View arg0, MotionEvent event) {
Log.d("Code777","Touch is being called finger");
if(event.getAction() == MotionEvent.ACTION_MOVE) {
Log.d("Code777", "Move event detected, ignored!");
return false;
}
// Further processing ..
}
或使用开关来区分所有相关事件。
请参阅MotionEvent class documentation以获取可能的操作列表。