android: using ListPreference and retrieving key string
I have a settings menu that pops up and in it is a ListPreference type menu. It is associated with a settings.xml file where there are 'array-strings' within it. It all works good but I don't know how to retrieve the users preference.
As an example, let's say the user picks a color (red, green, or blue). The list that I've made within my 'array-strings' contain the text red, green, and blu开发者_JS百科e. Within my code, I would like to do something if the user has chosen red, something else if they choose blue, etc., etc. Would I use a 'case' statement or an 'if' statement? And most importantly, how would I retrieve the users preference - the key? (am I checking for a boolean?)
If you are using ListPreference and you haven't disabled Persistent state, you can read the selected value from the SharedPreferences, after the setting is completed.
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
prefs.getString(yourkey, "defvalue");
Also you can subscribe to onClick
event, and you use the code Rpond mentioned.
If your list is being shown in a Dialog then you need to specify an OnClickListener which will call an onClick method. Check the example below. In the example the index passed to the onClick is the index of the item in the array.
new AlertDialog.Builder(this).setTitle("Settings").setItems(R.array.colors, new DialogInterface.onClickListener() { void onClick(DialogInterface d, int index) {
switch(index) {
CASE 0: // do something
CASE 1: // do something else}}};
精彩评论