要使用PreferenceFragment,你需要進行以下步驟:
public class MyPreferenceFragment extends PreferenceFragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.preferences);
}
}
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<PreferenceCategory android:title="Category 1">
<CheckBoxPreference
android:key="pref_key_checkbox"
android:title="Checkbox Preference"
android:summary="This is a checkbox preference"
android:defaultValue="false" />
</PreferenceCategory>
<PreferenceCategory android:title="Category 2">
<ListPreference
android:key="pref_key_list"
android:title="List Preference"
android:summary="This is a list preference"
android:entries="@array/list_entries"
android:entryValues="@array/list_entry_values"
android:defaultValue="1" />
</PreferenceCategory>
</PreferenceScreen>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getFragmentManager().beginTransaction()
.replace(android.R.id.content, new MyPreferenceFragment())
.commit();
}
}
這樣,你就可以在你的應用程序中使用PreferenceFragment來創建和管理首選項設置了。