爱玺玺

爱玺玺的生活日记本。wx:lb87626

Android sharedPreferences对象保存值永久保存,直到删除软件

package cn.jianhaozhan.activity;


import cn.jianhaozhan.ui.SettingView;

import android.app.Activity;

import android.content.SharedPreferences;

import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.view.View;

import android.view.View.OnClickListener;


public class SettingActivity extends Activity {

private SettingView sv_setting_update;

private SharedPreferences sp;// 保存信息


@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_setting);

sp = getSharedPreferences("config", MODE_PRIVATE);

sv_setting_update = (SettingView) findViewById(R.id.sv_setting_update);

sv_setting_update.setTitle("设置中心");

// 第二个参数是缺省值,就是这个参数没有就默认是什么值。

if (sp.getBoolean("update", true)) {

sv_setting_update.setDes("提示更新已开启");

sv_setting_update.setCheckBox(true);

} else {

sv_setting_update.setDes("提示更新已关闭");

sv_setting_update.setCheckBox(false);

}

sv_setting_update.setCheckBox(true);

// 问题1,点击checkbox发信描述信息没有改变,原因是因为checkbox天生是有点击事件和获取焦点事件,当点击时它会执行自带的点击事件,而不会执行条目的点击事件

// 解决方法,在样式文件去掉checkbox自带的事件

// 问题2,没有保存用户的操作,后退再返回没有保存

sv_setting_update.setOnClickListener(new OnClickListener() {


@Override

public void onClick(View v) {

Editor editor = sp.edit();

if (sv_setting_update.isChecked()) {

sv_setting_update.setDes("提示更新已关闭");

sv_setting_update.setCheckBox(false);

// 保存状态

editor.putBoolean("update", false);

} else {

sv_setting_update.setDes("提示更新已开启");

sv_setting_update.setCheckBox(true);

// 保存状态

editor.putBoolean("update", true);

}

editor.commit();

}

});

}

}


发表评论:

Powered By Z-BlogPHP 1.4 Deeplue Build 150101

Copyright Your WebSite.Some Rights Reserved.

蜀ICP备11021721号-5