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;
			}
		});
    }

	
}


郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。