我是android开发的初学者,我尝试实现一个使用sharedpreferences保存复选框的类。它到目前为止工作,我可以看到一切,并检查模拟器中的复选框。但单击“保存”按钮会导致我的应用程序崩溃。也许TextView有问题?
继承人代码......
public class Settings extends Activity implements OnClickListener {
CheckBox checkBox;
TextView textView;
Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.settingslayout);
checkBox = (CheckBox) findViewById(R.id.checkBox1);
textView = (TextView) findViewById(R.id.textView1);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(this);
loadSavedPreferences();
}
private void loadSavedPreferences() {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
boolean checkBoxValue = sharedPreferences.getBoolean("CheckBox_Value", false);
if (checkBoxValue) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
}
private void savePreferences(String key, boolean value) {
SharedPreferences sharedPreferences = PreferenceManager
.getDefaultSharedPreferences(this);
Editor editor = sharedPreferences.edit();
editor.putBoolean(key, value);
editor.commit();
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
savePreferences("CheckBox_Value", checkBox.isChecked());
if (checkBox.isChecked())
textView.setText("Visited.");
else
textView.setText("Not Visited");
finish();
}
}
答案 0 :(得分:0)
试试这段代码:
@Override
public void onClick(View v) {
if (v.getId() == R.id.button1) {
// TODO Auto-generated method stub
savePreferences("CheckBox_Value", checkBox.isChecked());
if (checkBox.isChecked())
textView.setText("Visited.");
else
textView.setText("Not Visited");
finish();
}
}
答案 1 :(得分:0)
从OnClick(View v)
中删除finish()@Override
public void onClick(View v) {
// TODO Auto-generated method stub
savePreferences("CheckBox_Value", checkBox.isChecked());
if (checkBox.isChecked())
textView.setText("Visited.");
else
textView.setText("Not Visited");
}
如果你有"真正的崩溃"附上logcat。