ListPreference是Android中一個用于顯示可選項列表的首選項框架。可以通過以下步驟來使用ListPreference:
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="list_preference"
android:title="List Preference"
android:summary="Select an option from the list"
android:entries="@array/options"
android:entryValues="@array/options_values"
android:defaultValue="default_value" />
</PreferenceScreen>
<resources>
<string-array name="options">
<item>Option 1</item>
<item>Option 2</item>
<item>Option 3</item>
</string-array>
<string-array name="options_values">
<item>value1</item>
<item>value2</item>
<item>value3</item>
</string-array>
</resources>
public class SettingsFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
}
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, new SettingsFragment())
.commit();
}
}