Monday, February 24, 2014

Create an Android PreferenceScreen using Java, not with XML

The Android preference fragment/activity is usually used to show a list of shared preferences for users to interact with. The list of the preferences is typically predefined using an XML file. But I wanted to define the list of preferences at run time because I had a variable list of preferences, which are known only at run time. This can be done by overriding the PreferenceFragment's or PreferenceActivity's onCreate method and manually creating and appending your own preferences to the root of the PreferenceScreen object.

The following code snippet for a PreferenceFragment shows how this is done. Make the appropriate changes for pre-Honeycomb Android versions.

//...etc...
public class MyPreferenceFragment extends PreferenceFragment {
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

//create my own PreferenceScreen
setPreferenceScreen(createMyPreference());
}
private PreferenceScreen createMyPrefenceScreen(){
//just an array of title strings for the preferences
String[] titles = { "Title1", "Title2", "Title3"};

//just an array of summary text strings for the preferences
String[] summaries = { "Summary1", "Summary2", "Summary3"};

PreferenceScreen root = getPreferenceManager().createPreferenceScreen(getActivity());
 
for (int i=0; i<titles.length; i++){
//create a preference
Preference pref = new Preference(getActivity());

//set the preference's title and summary text
pref.setTitle( titles[i]);
pref.setSummary( summaries[i]);
pref.setSelectable(false);

//append the preference to the PreferenceScreen
root.addPreference(pref);
}
 
return root;
}
}

The following screenshot shows how the resultant preference fragment/activity looks like.

No comments:

Related Posts with Thumbnails