如何动态创建 Android 首选项?
下面的模型可能比文字更能解释。本质上,我想要一个列表,其中用户可以动态添加/删除项目,并且每个项目都有可配置的设置屏幕。
因此,这里有两个关键:
- 添加到主首选项屏幕
- 启动 当按下某个项目时的activityForResult。本次活动将展示 另一个首选项视图(滑块、复选框等),用户可以在其中 可以操作这些,然后返回要存储的新值 一个数据结构。
图片:
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:
- Adding to the main preferences screen
- 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:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我建议沿着 Fragments 的道路前进 - 特别是 PreferenceFragment: http://developer. android.com/reference/android/preference/PreferenceFragment.html
为什么我认为这对你来说很有效:
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:
您的问题有点模糊,但最好的解决方法可能是将用户的数据存储在数据库中(并使用标准的 CursorAdapter 和 CursorLoader 实例将此数据显示给用户),而不是试图将所有内容强制纳入首选项框架。
CursorAdapter
针对处理任意大的结果集进行了优化,而PreferenceActivity
和朋友确实可以更好地处理固定的数据集。首选项的设计旨在使其特定用例易于实现,但如果您的用例超出了该范围(听起来确实如此),那么将数据压缩到首选项模型中将会很麻烦。
如果您只是喜欢首选项 UI,您当然可以查看 Android 源代码以了解它是如何实现的,同时仍然让您自己的逻辑驱动该 UI 的变体。
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
andCursorLoader
instances to show this data to the user) rather than trying to force everything into the Preferences framework. TheCursorAdapter
is optimized for dealing with arbitrarily large result sets, whilePreferenceActivity
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.
实际上动态创建首选项屏幕很容易。您可以通过代码(在 API 演示示例应用中搜索
PreferenceFromCode.java
)或通过展开可编写的 XML 文件 (PreferencesFromXml.java
) 来完成此操作。困难的是为用户提供一个合理的 UI 和存储后端来编写和存储这些动态偏好集合。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.