The Preference Activity

We can create ourselves preference activity in our android applications, but this is a tedious work, we have to operate every thing by ourself, e.g. rectrieve data from shared preference and set controls status, store data in shared preference and so on. 

Thanks for android preferences framework, all the things become simple.Following three setps below, we can make a useful preference acitvity.

The activity looks like:


First, Defining a Preference Screen Layout in XML

An exmaple layout file as follows:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
  xmlns:android="http://schemas.android.com/apk/res/android">
  <CheckBoxPreference
    android:key="PREF_AUTO_UPDATE"
    android:title="Auto refresh"
    android:summary="Select to turn on automatic updating" 
    android:defaultValue="true"
  />      
               
  <ListPreference
   android:key="PREF_UPDATE_FREQ"
   android:title="Refresh frequency"
   android:summary="Frequency at which to refresh earthquake list"
   android:entries="@array/update_freq_options"
   android:entryValues="@array/update_freq_values"
   android:dialogTitle="Refresh frequency"
   android:defaultValue="60"
  />
  
  <ListPreference
    android:key="PREF_MIN_MAG"
    android:title="Minimum magnitude"
    android:summary="Select the minimum magnitude earthquake to report"
    android:entries="@array/magnitude_options"
    android:entryValues="@array/magnitude"
    android:dialogTitle="Magnitude"
    android:defaultValue="3"
  />
</PreferenceScreen>

Second,Create a class inherits from PreferenceActivity

This class is used to host preference hierarchy defined using the preferences xml file.

The code looks like:

public class Preferences extends PreferenceActivity {

  @Override
  public void onCreate(Bundle icicle) {
	
    super.onCreate(icicle);
    addPreferencesFromResource(R.xml.userpreferences);	
  }  
}

R.xml.userpreferences is the file we create in first setp.

Third, Add Shared Preferences Change Listener 

The code snippet as follows:

public class MyActivity extends Activity implements
OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle SavedInstanceState) {
// Register this OnSharedPreferenceChangeListener
Context context = getApplicationContext();
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(context);
prefs.registerOnSharedPreferenceChangeListener(this);
}
public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
// TODO Check the shared preference and key parameters and change UI or
// behavior as appropriate.
}
}


 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

                
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值