因为我无法在Android 2.2中使用PreferenceFragment,所以我想从XML源创建一个ListView并将其显示在普通的Fragment中。我有这个XML lyout:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >
<CheckBoxPreference
android:summary="This is a CheckBox"
android:title="CheckBox"
android:defaultValue="false" />
</PreferenceScreen>
是否可以从中创建ListView?我认为来自addPreferencesFromResource
的方法PreferenceActivity
做同样的事情,但这是如何工作的?
答案 0 :(得分:1)
...
// fragments are not used at all and we instead, use the older
// PreferenceActivity APIs.
// Add 'notifications' preferences, and a corresponding header.
addPreferencesFromResource(R.xml.pref_general);
// Add 'notifications' preferences, and a corresponding header.
PreferenceCategory fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_notifications);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_notification);
// Add 'data and sync' preferences, and a corresponding header.
fakeHeader = new PreferenceCategory(this);
fakeHeader.setTitle(R.string.pref_header_data_sync);
getPreferenceScreen().addPreference(fakeHeader);
addPreferencesFromResource(R.xml.pref_data_sync);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences to
// their values. When their values change, their summaries are updated
// to reflect the new value, per the Android Design guidelines.
bindPreferenceSummaryToValue(findPreference("example_text"));
bindPreferenceSummaryToValue(findPreference("example_list"));
bindPreferenceSummaryToValue(findPreference("notifications_new_message_ringtone"));
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
pref_general.xml
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<CheckBoxPreference
android:key="example_checkbox"
android:title="@string/pref_title_social_recommendations"
android:summary="@string/pref_description_social_recommendations"
android:defaultValue="true" />
<!-- NOTE: EditTextPreference accepts EditText attributes. -->
<!-- NOTE: EditTextPreference's summary should be set to its value by
the activity code. -->
<EditTextPreference
android:key="example_text"
android:title="@string/pref_title_display_name"
android:defaultValue="@string/pref_default_display_name"
android:selectAllOnFocus="true"
android:inputType="textCapWords"
android:capitalize="words"
android:singleLine="true"
android:maxLines="1" />
<!-- NOTE: Hide buttons to simplify the UI. Users can touch outside the dialog to
dismiss it. -->
<!-- NOTE: ListPreference's summary should be set to its value by the
activity code. -->
<ListPreference
android:key="example_list"
android:title="@string/pref_title_add_friends_to_messages"
android:defaultValue="-1"
android:entries="@array/pref_example_list_titles"
android:entryValues="@array/pref_example_list_values"
android:negativeButtonText="@null"
android:positiveButtonText="@null" />
</PreferenceScreen>
希望这有帮助!