Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:
http://i.stack.imgur.com/eZsfh.png

like image 295
mister-f Avatar asked Jan 25 '12 05:01

mister-f


2 Answers

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.

like image 142
Davek804 Avatar answered Oct 31 '22 15:10

Davek804


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.

like image 24
mlc Avatar answered Oct 31 '22 16:10

mlc