您的当前位置:首页正文

[Android UI] ListPreference 动态改变Summary

2024-11-10 来源:个人技术集锦
首先该类实现 OnSharedPreferenceChange<wbr style="line-height:25px">Listener</wbr>接口

onCreate方法中进行注册
SharedPreferences prefs =<wbr style="line-height:25px">PreferenceManager.getDefaultSharedPreferen<wbr style="line-height:25px">ces(this);</wbr></wbr>
prefs. registerOnSharedPreferen<wbr style="line-height:25px">ceChangeListener</wbr>(this);

重写 onSharedPreferenceChange<wbr style="line-height:25px">d 方法</wbr>



以下是我的代码,我没时间整理代码,大家将就的看吧,有问题提问。我想我应该说清楚流程了."color"为listpreference的key
package com.h3c.AndVNC;

import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.EditTextPreference;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceManager;
import android.preference.Preference.OnPreferenceChangeListener;
import android.preference.Preference.OnPreferenceClickListener;
import android.widget.Toast;

public class SettingPage extends PreferenceActivity implements OnPreferenceChangeListener,   
OnPreferenceClickListener,OnSharedPreferenceChangeListener {
	
	ListPreference lp;
	EditTextPreference et;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		addPreferencesFromResource(R.xml.preferences);
		
		lp = (ListPreference)findPreference("color");
		et = (EditTextPreference)findPreference("repeater");
		lp.setSummary(lp.getEntry());
		et.setSummary(et.getText());
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
        prefs.registerOnSharedPreferenceChangeListener(this); 
//		lp.setOnPreferenceChangeListener(this);
//		lp.setOnPreferenceClickListener(this);
	}
	
	

	@Override
	public boolean onPreferenceChange(Preference preference, Object newValue) {
		// TODO Auto-generated method stub
		if(preference.getKey().equals("color"))  
        { 
			Toast.makeText(SettingPage.this,"s"+lp.getEntry(), Toast.LENGTH_SHORT).show();
//			lp.setSummary(lp.getEntry());
        }
		return true;
	}

	@Override
	public boolean onPreferenceClick(Preference preference) {
		// TODO Auto-generated method stub
		if(preference.getKey().equals("color"))  
        { 
//			lp.setSummary(lp.getEntry());
			Toast.makeText(SettingPage.this,lp.getEntry(), Toast.LENGTH_SHORT).show();
        }
		return false;
	}

	@Override
	public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
		// TODO Auto-generated method stub
		if(key.equals("color")){
			lp.setSummary(lp.getEntry());
		}
		if(key.equals("repeater")){
			et.setSummary(et.getText());
		}
	} 	
}



Top