2012-02-17 51 views
0

我在我的應用程序中實現振動功能時遇到了一些問題。 我的代碼是:Android:振動

public class VibrationActivity extends Activity { 

private Vibrator vib; 

private long[] pattern = { 0, 500, 200, 500 }; 

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 

vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE); 

} 

public void onClick(View v) { 
int id = v.getId(); 

if (id == R.id.button1) { 
vib.vibrate(pattern, -1); 
} 
} 

} 

我宣佈using語句在清單中也如此,這不是問題。當我點擊一個按鈕時,實際上並沒有發生任何事情......任何人有任何想法?

在此先感謝!

+1

哪裏是按鈕??? – 2012-02-17 10:33:46

+1

不要忘記爲您的按鈕註冊onClickListener。 – Jave 2012-02-17 10:37:13

+0

在onClick事件中,有一系列按鈕,但我只是在上面的代碼snippit中隱藏了一個按鈕。 – Shaw 2012-02-17 10:37:54

回答

3

使用此代碼:

public class testVibrate extends Activity { 
    /** Called when the activity is first created. */ 
    private Vibrator vib; 
    private long[] pattern = { 0, 500, 200, 500 }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 
     vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE); 
     findViewById(R.id.button1).setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       vib.vibrate(pattern, -1); 
      } 
     }); 
    } 
0

在你的onCreate()使用方法:

setContentView(R.layout.main); 
vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE); 

Button btn = (Button)findViewById(R.id.button1); 
btn.setOnClickListener(new OnClickListener(){ 
    public void onClick(View view) { 
     vib.vibrate(pattern, -1); 
    } 

}); 
0

你必須以找到其ID按鈕膨脹佈局。 ,然後將偵聽器附加到該按鈕。

public class VibrationActivity extends Activity { 
    private Vibrator vib; 

    private Button button; 

    private long[] pattern = { 0, 500, 200, 500 }; 

    @Override 
    public void onCreate(Bundle savedInstanceState) 
    { 
     super.onCreate(savedInstanceState); 

     setContentView(R.layout.your_layout); 

     vib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE); 

     button = (Button) findViewById(R.id.button1); 

     button.setOnClickListener(mOnClickListener); 
    } 

    private OnClickListener mOnClickListener = new OnClickListener() 
    { 

     @Override 
     public void onClick(View v) 
     { 
      int id = v.getId(); 

      if (id == R.id.button1) 
      { 
       vib.vibrate(pattern, -1); 
      } 
     } 
    }; 

}