mister-f
mister-f

Reputation: 440

How can I dynamically create an Android Preference?

A mockup is below that probably explains better than words. Essentially, I want a list where items can be added/removed dynamically by the user, and each item has configurable settings screen.

So there are two keys here:

  1. Adding to the main preferences screen
  2. Starting an activityForResult when an item is pressed. This activity will show another preferences view (sliders, checkboxes, etc) where the user can manipulate these and then return the new values to be stored in a data structure.

Image:
https://i.sstatic.net/eZsfh.png

Upvotes: 19

Views: 5731

Answers (3)

mlc
mlc

Reputation: 1718

Your question is a little bit vague, but probably this is best solved by storing the user's data in a database (and using standard CursorAdapter and CursorLoader instances to show this data to the user) rather than trying to force everything into the Preferences framework. The CursorAdapter is optimized for dealing with arbitrarily large result sets, while PreferenceActivity and friends really work better with a fixed set of data.

The Preferences stuff is designed to be easy to implement for its specific use case, but if your use case falls out of that scope — and it sounds like it does — it's going to be a hassle to squeeze your data into a preferences model.

If you just like the Preferences UI, you can of course peek at the Android source code to see how it is implemented while still letting your own logic drive a variant of that UI.

Upvotes: 1

Sparky
Sparky

Reputation: 8477

Actually creating the preference screens dynamically is easy. You can do it in code (search the API Demos sample app for PreferenceFromCode.java) or by expanding an XML file that you can write (PreferencesFromXml.java). What's going to be hard is coming up with a sensible UI and storage back-end for the user to compose and store these dynamic preference collections.

Upvotes: -1

Davek804
Davek804

Reputation: 2804

I would suggest heading down the road of Fragments - specifically PreferenceFragment: http://developer.android.com/reference/android/preference/PreferenceFragment.html

Why I think this will work well for you:

Furthermore, the preferences shown will follow the visual style of system preferences. It is easy to create a hierarchy of preferences (that can be shown on multiple screens) via XML. For these reasons, it is recommended to use this fragment (as a superclass) to deal with preferences in applications.

Upvotes: 1

Related Questions