2015-09-25 24 views
0

嘿,所以我遇到了一個問題,我需要能夠在方法中使用手勢檢測器,所以我可以調用上述方法中的方法我將粘貼代碼,但基本上它不能達到我的內心聲明,因此它會拋出一個錯誤!方法中的手勢檢測

private static final int SWIPE_MIN_DISTANCE = 120; 
private static final int SWIPE_MAX_OFF_PATH = 250; 
private static final int SWIPE_THRESHOLD_VELOCITY = 200; 
private GestureDetector gestureDetector; 
View.OnTouchListener gestureListener; 


@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    gestureDetector = new GestureDetector(this, new MyGestureDetector()); 
    gestureListener = new View.OnTouchListener() { 
     public boolean onTouch(View v, MotionEvent event) { 
      return gestureDetector.onTouchEvent(event); 
     } 
    }; 

然後,當我去調用類的使用姿勢檢測:

public void notification() { 
    final AchievementUnlocked achievementUnlocked = new AchievementUnlocked(MainActivity.this) 
    achievementUnlocked.getAchievementView().setOnTouchListener(gestureListener); 
    class MyGestureDetector extends GestureDetector.SimpleOnGestureListener { 

     @Override 
     public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { 
      try { 
       if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) 
        return false; 
       // left to right swipe 
       if(e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { 
       achievementUnlocked.dismiss(); 
       } 
       // right to left swipe 
       else if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) { 

       } 
      } catch (Exception e) { 
       // nothing 
      } 
      return false; 
     } 

如果我這樣做,我的代碼不能解析符號「MyGestureDetector」的這部分得到一個錯誤:

gestureDetector = new GestureDetector(this, new MyGestureDetector()); 

回答

1

您不能在方法中聲明常規的Java類。在notification()方法之外移動MyGestureDetector。你裏面調用

+0

好吧,我這樣做,但現在我不能訪問通知方法裏面的方法? –

+0

@SkylerMartin:Notification方法中沒有「方法」。我認爲你指的是「achievementUnlocked」。也許'MyGestureDetector'應該在一個字段中保存'AchievementUnlocked'實例。或者,也許'MyGestureDetector'應該做其他事情,比如在事件總線上發佈消息(例如,綠色機器人的EventBus),然後由其他地方的'AchievementUnlocked'實例拾取。 – CommonsWare

0

移動MyGestureDetector外及更換方法(如achievementUnlocked.dismiss();)是靜態

+0

我不能讓它變成靜態的,否則我的變量都會出錯! –