首页 > 代码库 > android PreferenceScreen使用笔记

android PreferenceScreen使用笔记


preference.xml

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <Preference android:title="基本信息"
        android:layout="@layout/text_view"></Preference> <!--自己定义layout-->
    <CheckBoxPreference android:key="checkbox"
        android:title="性别"
        android:summary="男 ,女"/>
    <RingtonePreference android:key="ringtone"
        android:title="Ringtone Preference"
        android:showDefault="true"
        android:showSilent="true"
        android:summary="Pick a tone, any tone"/> 
<ListPreference android:summary="select a list"
    android:title="Type"
    android:entries="@array/my_array" <!--string-array-->
    android:entryValues="@array/my_array"
    android:key="list"/>
<EditTextPreference android:key="edit"
    android:dialogTitle="nihao"
    android:title="姓名"
    />

</PreferenceScreen>

**Activity.java

package com.lin.share;

import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.view.View;

public class TestPreferenctScreenActivity extends PreferenceActivity {
    /** Called when the activity is first created. */
    ListPreference  list;
    SharedPreferences prefs;
    EditTextPreference editTextPreference;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preference);
       prefs=PreferenceManager.getDefaultSharedPreferences(this);
        list=(ListPreference)findPreference("list");
        editTextPreference=(EditTextPreference)findPreference("edit");
        editTextPreference.setSummary(prefs.getString("edit","default"));
        
        editTextPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				// TODO Auto-generated method stub
				editTextPreference.setSummary(newValue.toString());
				editTextPreference.setDefaultValue(newValue);
				editTextPreference.setText(newValue.toString());
				return false;
			}
		});
        list.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
			
			@Override
			public boolean onPreferenceChange(Preference preference, Object newValue) {
				System.out.println("change"+newValue);
				list.setSummary(newValue.toString());
				list.setValue(newValue.toString());
				return false;
			}
		});
    }

	
}


android PreferenceScreen使用笔记