Android中PreferenceFregment使用完全攻略(2)

2.创建一个activity用于给PreferenceFragment 依附

package com.example.Androidpreferencefragment;

import android.app.Activity;
import android.os.Bundle;

public class SetPreferenceActivity extends Activity {

@Override
 protected void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);
 
  getFragmentManager().beginTransaction().replace(android.R.id.content,
                new PrefsFragment()).commit();
 }

}

3.创建PreferenceFragment

package com.example.androidpreferencefragment;

import android.annotation.SuppressLint;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.Preference.OnPreferenceChangeListener;

@SuppressLint("NewApi")
public class PrefsFragment extends PreferenceFragment implements OnSharedPreferenceChangeListener{

@Override
 public void onCreate(Bundle savedInstanceState) {
  // TODO Auto-generated method stub
  super.onCreate(savedInstanceState);

// Load the preferences from an XML resource
  addPreferencesFromResource(R.xml.preferences);
 }

@Override
 public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
  // TODO Auto-generated method stub
  // Set summary to be the user-description for the selected value
  if(!key.equals(MainActivity.PRF_CHECK))
  {
   Preference connectionPref = findPreference(key);
   connectionPref.setSummary(sharedPreferences.getString(key, ""));
  }
 }

@Override
 public void onResume() {
  super.onResume();
  getPreferenceManager().getSharedPreferences().registerOnSharedPreferenceChangeListener(this);

}

@Override
 public void onPause() {
  getPreferenceManager().getSharedPreferences().unregisterOnSharedPreferenceChangeListener(this);
  super.onPause();
 }

}

implements OnSharedPreferenceChangeListener 是用于监听SharedPreference是否改变的。这里主要的作用是当SharedPreference改变的时候及时更新界面中preference的summary,提供一个更好的交互。注意在OnResume和OnPause中要注册和卸载监听器,维护activity中的生命周期。

注:不能给每个preference设置OnChangeListener来更新界面中preference的summary,这样会阻止系统存储preference.xml.

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:http://www.heiqu.com/425fee7d09cdc9852b88f6ecef087bc7.html