嗨,我遇到了“保存复选框的状态”的问题。在我的情况下:检查状态 - 启用声音,取消选中状态 - 禁用它们。在我的 options.xml 上,我进行了设置:
<CheckBox
android:id="@+id/bbutton_sound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/ebsound"
android:layout_marginTop="20.00dp"
android:checked="true"/>
问题是当我取消选中选项中的复选框时。退出应用程序并再次输入后,所有声音均已启用(这是正确的),但复选框保持未选中状态(应返回检查状态)。我不知道如何实现这一点。我试图通过 ondestroy 方法强制“检查状态”,但没有任何帮助。这是我的java代码:
package com.Pong;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.Toast;
public class Options extends Activity {
private CheckBox bbutton_sound;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
addListenerOnButton();
bbutton_sound.setChecked(true);
final MediaPlayer mpButtonClick = MediaPlayer.create(this, R.raw.menu_button_sound);
Button BackButton = (Button)findViewById(R.id.Back);
BackButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent MenuIntent = new Intent(Options.this,Menu.class);
Options.this.finish();
startActivity(MenuIntent);
mpButtonClick.start();
}
});
}
@Override
public void onPause() {
super.onPause();
save(bbutton_sound.isChecked());
}
@Override
public void onResume() {
super.onResume();
bbutton_sound.setChecked(load());
}
private void save(final boolean isChecked) {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean("check", isChecked);
editor.commit();
}
private boolean load() {
SharedPreferences sharedPreferences = getPreferences(Context.MODE_PRIVATE);
return sharedPreferences.getBoolean("check", true);
}
public void addListenerOnButton() {
bbutton_sound = (CheckBox) findViewById(R.id.bbutton_sound);
bbutton_sound.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
AudioManager volumeControl = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
volumeControl.setStreamMute(AudioManager.STREAM_MUSIC, false);
int maxVolume = volumeControl.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volumeControl.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, maxVolume);
Toast.makeText(Options.this,
"Sounds enabled", Toast.LENGTH_LONG).show();
} else if (((CheckBox) v).isChecked()==(false)){
AudioManager volumeControl = (AudioManager)getSystemService(Context.AUDIO_SERVICE);
volumeControl.setStreamMute(AudioManager.STREAM_MUSIC, true);
Toast.makeText(Options.this,
"Sounds disabled", Toast.LENGTH_LONG).show();
}
}
});
}
}
感谢您的任何帮助。