[英]Interesting android touch issue
我遇到的問題是我正在使用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;
}
您的代碼將在每次觸摸事件期間執行。 第一次激活時,可能會發生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
等等。
onTouchListener
通過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類文檔 。 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.