2011-09-30 18 views
0

我想確定在Android中觸發MotionEvent的UI控件。我有一個doubleTapDetector用於幾個UI控件的單DoubleTapDetector

public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 
    doubleTapDetector = new GestureDetector(this, new DoubleTapDetector()); 
} 

聲明

private class DoubleTapDetector extends GestureDetector.SimpleOnGestureListener {  
    @Override 
    public boolean onDoubleTap(MotionEvent e) { 
     String uiControlName = obtainUiControlName(e); 
     // Do something depends on uiControlName 
     return true; 
    }   

    private String obtainUiControlName(MotionEvent e) { 
     int deviceId = e.getDeviceId(); 
     switch (deviceId) { 
      case R.id.button1: return "Button1"; 
      case R.id.button2: return "Button2"; 
     } 
     return null; 
    }   
} 

放在兩個按鈕

Button button1 = (Button) findViewById(R.id.button1); 
    outcomeButton.setOnTouchListener(new OnTouchListener(){ 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      doubleTapDetector.onTouchEvent(event); 
      return true; 
     } 
    });   

Button button2 = (Button) findViewById(R.id.button2); 
    outcomeButton.setOnTouchListener(new OnTouchListener(){ 

     @Override 
     public boolean onTouch(View v, MotionEvent event) { 
      doubleTapDetector.onTouchEvent(event); 
      return true; 
     } 
    }); 

的問題是,DEVICEID總是等於0,我不能確定哪些觸發按鈕雙擊事件。有沒有辦法做到這一點,而不是爲每個按鈕實現兩個不同的doubleTapDetector?

回答

0

錯誤。 getDeviceId返回接收到觸摸的物理指針設備ID。不是小工具ID。

我覺得唯一的方法就是爲每個按鈕創建獨特的DoubleTapDetector,並在DoubleTapDetector類中存儲某種按鈕的ID。因爲onDoubleTap方法沒有提供足夠的有關輕敲發生的Widget的信息。

像這樣:

private class DoubleTapDetector extends GestureDetector.SimpleOnGestureListener { 
    int id; 
    DoubleTapDetector(int id){ 
     this.id = id; 
    } 
... 
+0

看來你是對的...順便說一下,我有onLongPress和onDoubleTap之間的一些干擾 - DoubleTap後** **總是長按被解僱了! [看看,PLZ!](http://stackoverflow.com/questions/7606921/why-android-onlongpress-always-is-fired-after-ondoubletap)它是什麼原因? – isabsent