How can I keep on adding preferences when i click one?

喜夏-厌秋 提交于 2019-12-31 03:58:12

问题


I have a problem. I want to give a user freedom to select a number of Bluetooth devices in my app. Now I dont know how many Bluetooth devices will there be so I was wondering is it possible to give user an option to click on "Add a new Bluetooth Device" custom preference and open up a new preference screen for him to select Bluetooth setting of new device?

In summary the display would look like:

Add a new Bluetooth Device..

If user adds one, it should then look like:

Bluetooth Device 1

Add a new Blutooth Device..

If user adds another one it should look like:

Bluetooth Device 1

Bluetooth Device 2

Add a new Bluetooth Device..

I know how to use standard preferences and basic coding. The only thing I want to know is how can I keep on adding settings for these devices at runtime.I will appreciate any help. Thanks.


回答1:


Not sure if I'm understanding this completely, but it sounds like you would want to add a preference for each bluetooth device. To do this, you would want to do something like this:

Inside of the function in which you add the bluetooth device:

SharedPreferences prefs = getDefaultSharedPreferences();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("BT" + nameOfDevice, whateverYouWantToStoreAboutTheDevice);
editor.commit();

If you want to retrieve all the preferences for each bluetooth device, you could get the Set of all keys in your SharedPreferences file, figure out which ones have the "BT" prefix, and pull each of those preferences. Something like this:

Set<String> keySet = prefs.getAll().keySet();
for(String key : keySet){
   if(key.startsWith("BT"){
       String theValue = prefs.getString(key, null);
       //Do whatever with that value
   }
}

However, it just dawned on me that it sounds like you're talking about dynamically adding Preference Views. That's something else entirely =).

Edit: Here's how to add a Preference with a View programmatically from your preferences Activity:

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.prefs);
        CheckBoxPreference checkbox = new CheckBoxPreference(this);
        checkbox.setTitle("This is a checkbox preference");
        ((PreferenceScreen)findPreference("PREFSMAIN")).addPreference(checkbox);
    }

In this example, I gave my PreferenceScreen a key of "PREFSMAIN". You could add any kind of Preference you wanted in this manner.




回答2:


Consider implementing your own preference activity and using http://developer.android.com/reference/android/preference/PreferenceManager.html



来源:https://stackoverflow.com/questions/5436241/how-can-i-keep-on-adding-preferences-when-i-click-one

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!