我在创建一个带有复选框的对话框。这个复选框如果选中则会在下次打开应用程序时显示对话框..我已经在共享偏好中保存了复选框状态,它会显示我是否选中了复选框,但对话框仍然在启动时打开..怎么了?
修改
//对话框 查看checkBoxView = View.inflate(this,R.layout.checkbox,null); CheckBox checkBox =(CheckBox)checkBoxView.findViewById(R.id.checkbox); checkBox.setChecked(getFromSP( “复选框”));
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
private void saveInSp(String key,boolean value){
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
switch(buttonView.getId()){
case R.id.checkbox:
saveInSp("checkBox",isChecked);
break;
}
}
});
checkBox.setText("Never show it");
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
boolean hasBeenChecked = preferences.getBoolean("checkbox", false);
if (!hasBeenChecked) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" TITLE");
builder.setMessage(" blablabla ")
.setView(checkBoxView)
.setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}
答案 0 :(得分:1)
在调用AlertDialog.show()之前,您必须检查保存的值是否为共享首选项。
示例:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" TITLEs");
builder.setMessage(" blablabla ")
.setView(checkBoxView)
.setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
AlertDialog dialog = builder.create();
if (getFromSP("checkBox")) {
dialog.show();
}
答案 1 :(得分:1)
我会:
saveInSp
中删除OnCheckedChangeListener
并将其添加到活动中,例如saveInSp
MyActivity.this.saveInSp
然后,在初始化并显示警报之前......
SharedPreferences preferences = getApplicationContext().getSharedPreferences("PROJECT_NAME", android.content.Context.MODE_PRIVATE);
boolean hasBeenChecked = preferences.getBoolean("checkBox", false);
if (!hasBeenChecked) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(" TITLEs");
builder.setMessage(" blablabla ")
.setView(checkBoxView)
.setCancelable(false)
.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
}).show();
}