开发者

android: using ListPreference and retrieving key string

开发者 https://www.devze.com 2022-12-23 17:06 出处:网络
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

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}}}; 
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号