9

I'm new in Android. In my app i want to do something like this: I have a container and i want to add item dynamically to it, in one item there may be some fields, so tree would be 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 using preferences, cause i need store user's info in app, but don't know how. Can you help me, please?

frank
  • 105
  • 1
  • 6

1 Answers1

30

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.

Edric
  • 24,639
  • 13
  • 81
  • 91
Katharina
  • 1,612
  • 15
  • 27
  • 2
    Important to add any preference category to the preference screen *before* adding any preferences to the category, or you will get a null pointer – Vin Norman Jul 31 '19 at 08:16