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

示例代码:

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";

	@Override
	protected 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监听的动作
	@Override
	public 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值