How to dynamically add preferences into preferences screen and bind their values?

我只是一个虾纸丫 提交于 2019-12-03 14:48:27
Katharina

You need to create an xml file with an empty PreferenceScreen:

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">

</PreferenceScreen>

Then in your PreferenceFragmentyou must call the following method in your onCreate(Bundle savedInstanceState) {...}

addPreferencesFromResource(R.xml.pref_empty);

Afterwards you can add Preferences like this:

PreferenceScreen preferenceScreen = this.getPreferenceScreen();

// create preferences manually
PreferenceCategory preferenceCategory = new PreferenceCategory(preferenceScreen.getContext());
preferenceCategory.setTitle("yourTitle");
// do anything you want with the preferencecategory here
preferenceScreen.addPreference(preferenceCategory);

Preference preference = new Preference(preferenceScreen.getContext());
preference.setTitle("yourTitle");
// do anything you want with the preferencey here
preferenceCategory.addPreference(preference);

Of course you can add preferences and categories in a loop to add them dynamically.

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