SharedPreferences 首选项使用实例

ch9share.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="这是一个首选项SharedPreference示例"/>
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="输入用户名:"/>
    <EditText android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/user"/>
    <Button android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/bt_OK"
        android:text="确定"
        android:gravity="center_horizontal"/>
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="首选项的设置为:"/>
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:id="@+id/tv"/>

</LinearLayout>

在res/xml/目录下创建ch9preference.xml:

<?xml version="1.0" encoding="UTF-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    android:key="setting"
    android:title="软件设置">
    <PreferenceCategory 
        android:key="basicSet"
        android:title="基本设置">
        <EditTextPreference android:key="username"
            android:title="账户"
            android:defaultValue=""
            android:summary="设置账户名"/>
        <CheckBoxPreference android:key="nightmode"
            android:title="夜间模式"
            android:summaryOn="已启用"
            android:summaryOff="未启用"/>
        <RingtonePreference 
            android:key="ringtone"
            android:title="铃声"
            android:showSilent="true"
            android:ringtoneType="alarm"
            android:summary="设置通知铃声"/>
    </PreferenceCategory>
    <PreferenceCategory android:key="textSet"
        android:title="本文设置">
        <ListPreference android:key="fontSize"
            android:title="字体大小"
            android:summary="设置字体大小"
            android:entries="@array/fontsize"
            android:entryValues="@array/fontsizevalue"
            android:dialogTitle="选择字体大小"/>
    </PreferenceCategory>
</PreferenceScreen>

编写string资源文件,string.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">BaseExample</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string name="a">假如给我三天光明</string>
    <string name="b">百年孤独</string>
    <string name="c">童年</string>
    <string name="d">四大名著</string>
    <string name="e">钢铁是怎样炼成的</string>
    <string name="f">城南旧事</string>
    
    <string-array name="fontsize">
        <item>小</item>
        <item>正常</item>
        <item>大</item>
    </string-array>
    <string-array name="fontsizevalue">
        <item>0</item>
        <item>1</item>
        <item>2</item>
    </string-array>
    

</resources>

创建首选项的活动类,SetPreferenceActivity.java:

package com.example.ch9;


import com.example.baseexample.R;

import android.os.Bundle;
import android.preference.PreferenceActivity;

public class SetPreferenceActivity extends PreferenceActivity {
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.ch9preference);
	}
}

主类SharedPreferencesActivity.java:

package com.example.ch9;

import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.example.baseexample.R;

import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class SharedPreferencesActivity extends Activity {
	private TextView tv;
	private EditText edtUser;
	private Button bt_OK;
	private SharedPreferences pref;
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.ch9share);
		
		edtUser = (EditText)findViewById(R.id.user);
		bt_OK = (Button)findViewById(R.id.bt_OK);
		bt_OK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				pref = getSharedPreferences("com.example.baseexample_preferences",MODE_WORLD_READABLE);
				Editor editor = pref.edit();
				String userName = edtUser.getText().toString();
				editor.putString("username", userName);
				editor.commit();
				showSetting();
			}
		});
	}
	
	public boolean onCreateOptionsMenu(Menu menu){
		menu.add(Menu.NONE,Menu.FIRST+1,1,"设置");
		menu.add(Menu.NONE,Menu.FIRST+2,2,"退出");
		return true;
	}
	
	public boolean onOptionsItemSelected(MenuItem item){
		switch(item.getItemId()){
		case Menu.FIRST+1:
			Intent intent = new Intent();
			intent.setClass(this, SetPreferenceActivity.class);
			startActivityForResult(intent, 1);
			break;
		case Menu.FIRST+2: 
			finish();
			break;
		}
		return super.onOptionsItemSelected(item);
	}
	
	protected void onActivityResult(int requestCode,int resultCode,Intent data){
		super.onActivityResult(requestCode, resultCode, data);
		showSetting();
	}
	
	private void showSetting(){
		String settingStr;
		tv = (TextView)findViewById(R.id.tv);
		pref = getSharedPreferences("com.example.ch9_preferences",MODE_WORLD_READABLE);
		String username=pref.getString("username", "");
		settingStr = "您设置的账户名为:"+username+"\n";
		
		Boolean nightmode = pref.getBoolean("nightmode", false);
		if(nightmode){
			settingStr = settingStr +"夜间模式:已启用\n";
		}else{
			settingStr = settingStr +"夜间模式:未启用\n";
		}
		String fontSize = pref.getString("fontSize", "2");
		if(fontSize.equals("0")){
			settingStr = settingStr+"字体:小"+"\n";
		}else if(fontSize.equals("1")){
			settingStr = settingStr+"字体:正常"+"\n";
		}
		else if(fontSize.equals("2")){
			settingStr = settingStr+"字体:大"+"\n";
		}
		
		tv.setText(settingStr);
		
		Map<String, Object> map = (Map<String, Object>) pref.getAll();
		Set<String> s = map.keySet();
		Iterator<String> iterator = s.iterator();
		while(iterator.hasNext()){
			System.out.println(iterator.next());
		}
	}
}




你可能感兴趣的:(SharedPreferences 首选项使用实例)