2012-05-18 61 views
0

我想在我的活動中設置圖像按鈕(pushClick),以啓用用於旋轉針圖形的onTouchEvents。不幸的是,無論我是否點擊圖像按鈕,onTouchEvent都處於活動狀態。我怎樣才能防止onTouchEvent發射,直到點擊圖像按鈕後?開始onTouchEvent之後onClick事件

public void pushClick(View pushClick) { 
    switch (pushClick.getId()) { 
    case R.id.btn_push: 

     make(degrees); 

    } 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    switch (event.getAction()) { 
    case MotionEvent.ACTION_DOWN: 
     startRotating(); 
     break; 
    case MotionEvent.ACTION_UP: 
     stopRotating(); 
     break; 
    } 

    return super.onTouchEvent(event); 
} 

private void startRotating() { 
    returnRotating = false; 

    if (!keepRotating) { 
     keepRotating = true; 

     final Handler handler = new Handler(); 
     handler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       if (keepRotating) { 
        degrees = (degrees + 1) % 360; 
        make(degrees); 

        handler.postDelayed(this, INTERVAL); 
       } 
      } 
     }, INTERVAL); 
    } 
} 

private void stopRotating() { 
    keepRotating = false; 

    if (!returnRotating) { 
     returnRotating = true; 

     final Handler handler = new Handler(); 

     handler.postDelayed(new Runnable() { 
      @Override 
      public void run() { 
       if (returnRotating) { 
        degrees = (degrees - 1) % 360; 
        make(degrees); 

        handler.postDelayed(this, INTERVAL); 
       } 
      } 
     }, INTERVAL); 
    } 
} 

回答

1

我敢打賭,有一個更好的方式來做到這一點,但在這裏把我的頭頂部:

private boolean buttonClicked = false; 

public void pushClick(View pushClick) { 
    switch (pushClick.getId()) { 
    case R.id.btn_push: 
     buttonClicked = true; 
     make(degrees); 

    } 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) { 
    if(buttonClicked) 
    { 
     switch (event.getAction()) { 
     case MotionEvent.ACTION_DOWN: 
      startRotating(); 
      break; 
     case MotionEvent.ACTION_UP: 
      stopRotating(); 
      break; 
     } 
    } 

    return super.onTouchEvent(event); 
} 
+0

這實際上就像一個魅力!我試圖找出如何使用int將on()添加到onTouchEvent,但是有很多語法問題。萬分感謝! – n00bdev

0

您還可以添加OnTouchListener(無論從任何瀏覽你想要它附着到)當你的圖像按鈕被按下,並再次點擊時將其刪除(如果這是你想要的)。

+0

我曾嘗試將onTouchListener作爲布爾值移動到圖像按鈕部分,但運行時會關閉,因此我將其支持以支持更簡單的方法。 – n00bdev