How to dynamically add settings to the settings screen and bind their values?

I am new to Android. In my application, I want to do something like this: I have a container and I want to add an element dynamically to it, there may be some fields in one element, so the tree will look like this:

main container

- item 1
   --field 1
   --field 2
   ...
   --field n
 - item 2
   --field 1
   --filed 2
.......
 - item n
   --field 1
   --field 2
   ...
   field n

I want to do this with the settings, because I need to store user information in the application, but I don’t know how to do it. could you help me?

+4
source share
1 answer

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 PreferenceFragmentyou should call the following method inonCreate(Bundle savedInstanceState) {...}

addPreferencesFromResource(R.xml.pref_empty);

Subsequently, you can add Preferenceas follows:

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);

, , .

+16

All Articles