Android: how to get list of all preference xml's for my app and read them?

前端 未结 3 398
挽巷
挽巷 2020-12-16 04:16

how to get list of all application preferences for application,

1. I am saving shared preference in this manner

3条回答
  •  旧巷少年郎
    2020-12-16 04:52

    public class Preferences extends PreferenceActivity {
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            // load the XML preferences file
            addPreferencesFromResource(R.xml.preferences);
        }
    }
    

    Then in your main class, you can refer to the preferences

    public class DrinkingBuddy extends Activity 
                               implements OnSharedPreferenceChangeListener {
    
        private int weight;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    
            // register preference change listener
            prefs.registerOnSharedPreferenceChangeListener(this);
    
            // and set remembered preferences
            weight = Integer.parseInt((prefs.getString("weightPref", "120");
            // etc
        }
    
        // handle updates to preferences
        public void onSharedPreferenceChanged(SharedPreferences prefs, String key) {
            if (key.equals("weightValues")) {
                weight = Integer.parseInt((prefs.getString("weightPref", "120");
            }
            // etc
        }
    }
    

    The saving of preference updates is handled for you.

    (Not too sure about public/private declarations!).

提交回复
热议问题