我正在尝试使用切换按钮。
以下是代码:
public class Activity2 extends AppCompatActivity {
public Activity2() {
super();
}
AudioManager audio;
@Nullable
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.activity2, container, false);
}
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
}
public void onToggleClicked(View view) {
//audio =new AudioManager();
// Is the toggle on?
boolean on = ((ToggleButton) view).isChecked();
if (on) {
// Enable vibrate
audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
AudioManager.VIBRATE_SETTING_ON);
audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
AudioManager.VIBRATE_SETTING_ON);
} else {
// Disable vibrate
audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER,
AudioManager.VIBRATE_SETTING_OFF);
audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION,
AudioManager.VIBRATE_SETTING_OFF);
}
}
}
这是xml:
<ToggleButton
android:id="@+id/togglebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="Vibrate on"
android:textOff="Vibrate off"
android:onClick="onToggleClicked"/>
我正在尝试使用切换按钮,它给了我错误:
尝试调用虚方法'void 在null上的android.media.AudioManager.setVibrateSetting(int,int)' 对象参考。
请帮助......谢谢!
答案 0 :(得分:0)
您忘记初始化
AudioManager
和ToggleButton
您需要在 AudioManager
ToggleButton
和 onCreate()
ToggleButton ToggleButton;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
audio = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
ToggleButton = (ToggleButton) findViewById(R.id.togglebutton);
}