gpt4 book ai didi

java - Android 在复选框上振动

转载 作者:行者123 更新时间:2023-12-01 09:55:47 26 4
gpt4 key购买 nike

我想构建一个简单的应用程序,该应用程序在单击复选框时振动并在再次单击后停止:

目前看起来像这样:

import android.content.Context;
import android.os.Vibrator;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;

public class MainActivity extends AppCompatActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
final CheckBox vibrateCheckBox = (CheckBox) findViewById(R.id.checkPowerStrong);

if(vibrateCheckBox.isChecked()) {
while(vibrateCheckBox.isChecked()) {
vibrator.vibrate(1000);
}
} else {
vibrator.cancel();
}

}
}

但我确实收到错误:

Caused by: java.lang.IllegalStateException: System services not available to Activities before onCreate()

我授予 list 振动权限:

如何解决这个问题

最佳答案

它完全符合您的要求。做这样的事情

final Vibrator vibrator = (Vibrator) MainActivity.this.getSystemService(Context.VIBRATOR_SERVICE);
final CheckBox vibrateCheckBox = (CheckBox) findViewById(R.id.checkPowerStrong);

final Handler handler = new Handler();

final Runnable r = new Runnable() {
public void run() {
vibrator.vibrate(1000);
handler.postDelayed(this, 1000);
}
};

vibrateCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {

@Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if(vibrateCheckBox.isChecked()) {
handler.postDelayed(r, 100);
} else {
handler.removeCallbacks(r);
vibrator.cancel();
}

}
}
);

关于java - Android 在复选框上振动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37238742/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com