android - How to add ListPreference in this Activity? -
i newbie @ android development , trying implement settings activity can take user preferences. settings activity includes code handle edit preference changes.the module implemented android 3.0 , above hence settings fragment used.
public class settingsactivity extends preferenceactivity { @override protected void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); getfragmentmanager().begintransaction().replace(android.r.id.content, new settingsfragment()).commit(); } public static class settingsfragment extends preferencefragment implements sharedpreferences.onsharedpreferencechangelistener{ @override public void oncreate(bundle savedinstancestate) { super.oncreate(savedinstancestate); // load preferences xml resource addpreferencesfromresource(r.xml.pref_general); } @override public void onresume(){ super.onresume(); getpreferencescreen().getsharedpreferences().registeronsharedpreferencechangelistener(this); } @override public void onpause(){ super.onpause(); getpreferencescreen().getsharedpreferences().unregisteronsharedpreferencechangelistener(this); } @override public void onsharedpreferencechanged(sharedpreferences sharedpreferences,string key){ if(key.equals("location")){ preference loc_preference=findpreference("location"); loc_preference.setsummary(sharedpreferences.getstring(key,"")); } } }
}
this pref_gen.xml file
<preferencescreen xmlns:android="http://schemas.android.com/apk/res/android"> <edittextpreference android:key="@string/pref_loc_key" android:dialogmessage="@string/location_dialog_message" android:dialogtitle="@string/location_dialog" android:title="@string/pref_loc_label" android:defaultvalue="@string/pref_default_loc" android:selectallonfocus="true" android:singleline="true" /> <listpreference android:key="@string/pref_unit_key" android:dialogtitle="@string/unit_dialog_message" android:title="@string/pref_unit_label" android:defaultvalue="@string/pref_default_unit" android:entries="@array/pref_unit_options" android:entryvalues="@array/pref_unit_values" />
this arrays.xml file
<string-array name="pref_unit_options"> <item>metric</item> <item>imperial</item> </string-array> <string-array name="pref_unit_values"> <item>1</item> <item>0</item> </string-array>
can me add list preference module in settings fragment method along listener? have gone through other posts somehow cant modify accordingly.
you can use getpreference
reference listpreference in java , register listener on it.
listpreference unit_preference = mcontext.getpreference(<key>); unit_preference .setonpreferencechangelistener(new onpreferencechangelistener() { public boolean onpreferencechanged(preference preference, object newvalue) { //do newvalue here } });
note: mcontext class variable of type context
. must set before calling begintransaction
:
mcontext = this;
Comments
Post a Comment