我目前正在使用 android studio 构建我的第一个 android 应用程序。我有一个按钮按下游戏,目前在游戏过程中按下按钮时它会振动。我想做一个切换来打开和关闭按钮。目前,我有这样的东西:
public void onCheckBoxClicked(View view){
Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
boolean checked = ((CheckBox)R.id.vibratecbx).isChecked();
if(checked){
}
else{
vibrate.cancel();
}
}
我收到有关不兼容类型的行 ((CheckBox)R.id.vibratecbx) 的错误,因此我需要对此进行修复,并查看如何切换实际的游戏的振动选项打开或关闭。 谢谢:)
这是主要的游戏文件部分,然后按下按钮:
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//vibrate on press
Vibrator vibrate = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
boolean isVibrator = vibrate.hasVibrator();
if(isVibrator)
vibrate.vibrate(50);
最佳答案
((CheckBox)R.id.vibratecbx) 不会给你一个 CheckBox。
如果您想使用您的 CheckBox,您需要从您扩充的 xml 中获取对它的引用。
例如,在您的 Activity 中,您可以在 onCreate 期间获取您的 Checkbox
private CheckBox myCheckBox;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCheckBox = (CheckBox) findViewById(R.id.vibratecbx);
}
然后您可以根据需要使用 myCheckBox。
编辑
您可以保存 CheckBox 的状态并在单击按钮时使用它。 这样您就可以在 onClickListener 中检查应用是否应该振动。
因此:
private CheckBox myCheckBox;
private Vibrator myVibrator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myCheckBox = (CheckBox) findViewById(R.id.vibratecbx);
myVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
....
myButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// ... your actions
if(myVibrator.hasVibrator() && myCheckBox.isChecked())
{
// Vibrate for 400 milliseconds
myVibrator.vibrate(400);
}
}
});
}
关于java - 需要打开或关闭振动器选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36750729/