要在Fragment中使用自定義的ListPreference,你可以按照以下步驟進行操作:
public class MyPreferenceFragment extends PreferenceFragmentCompat {
@Override
public void onCreatePreferences(Bundle savedInstanceState, String rootKey) {
setPreferencesFromResource(R.xml.preferences, rootKey);
}
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// 獲取自定義的ListPreference
ListPreference customListPreference = findPreference("custom_list_preference");
// 設置ListPreference的選項和默認值
CharSequence[] entries = {"Option 1", "Option 2", "Option 3"};
CharSequence[] entryValues = {"1", "2", "3"};
customListPreference.setEntries(entries);
customListPreference.setEntryValues(entryValues);
customListPreference.setDefaultValue("1");
}
}
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
<ListPreference
android:key="custom_list_preference"
android:title="Custom List Preference"
android:summary="Choose an option"
android:dialogTitle="Select an option" />
</PreferenceScreen>
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 使用FragmentManager將MyPreferenceFragment添加到布局中
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.preference_container, new MyPreferenceFragment())
.commit();
}
}
<FrameLayout
android:id="@+id/preference_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
這樣,你就可以在Fragment中使用自定義的ListPreference了。