Android开发————SharedPreferences学习笔记

来源:互联网 发布:java中的接口的作用 编辑:程序博客网 时间:2024/05/16 03:38

示例代码:

package com.example.sharedpreferences;import android.app.Activity;import android.app.AlertDialog;import android.content.Context;import android.content.SharedPreferences;import android.content.SharedPreferences.Editor;import android.os.Bundle;import android.widget.CheckBox;import android.widget.CompoundButton;import android.widget.CompoundButton.OnCheckedChangeListener;public class MainActivity extends Activity implements OnCheckedChangeListener {private CheckBox checkbox;private SharedPreferences sp;private static final String KEY_SHOW_DIALOG_AT_START = "showWelcomeDialogStart";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.fragment_main);// 要在之前进行sp = getSharedPreferences("settings", Context.MODE_PRIVATE);checkbox = (CheckBox) findViewById(R.id.checkbox);// 只有在获取到组件之后才可以进行后续的组件上的操作,否则会出现空指针错误// 此处的checked设置是由SharedPreferences中的配置数据进行设置的checkbox.setChecked(sp.getBoolean(KEY_SHOW_DIALOG_AT_START, false));// 对checkbox按键进行监听checkbox.setOnCheckedChangeListener(this);if (checkbox.isChecked()) {new AlertDialog.Builder(this).setTitle("欢迎").setMessage("你好欢迎使用我").setPositiveButton("关闭", null).show();}}// checkbox监听的动作@Overridepublic void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {// checkebox改变之后要改变一下SharedPreferences中的数据// 首先调用eidt进行编辑Editor e = sp.edit();// 将指定名称的数据变量进行改变e.putBoolean(KEY_SHOW_DIALOG_AT_START, isChecked);// 此时还没有存储只有提交之后才可以存储// 最后提交到该SharedPrefrences实体中去e.commit();}}

简易XML布局文件:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical" >    <CheckBox        android:id="@+id/checkbox"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="启动后呈现对话框" /></LinearLayout>


0 0
原创粉丝点击