如何在 Android 中更改 PreferenceScreen 的文本颜色和背景颜色

How to change text color and background color of PreferenceScreen in Android

如何在由 PreferenceFragmentCompat 膨胀的 PreferenceScreen 中更改文本和背景颜色?

已尝试 ,但该解决方案适用于 Preference Activity 而不是 PreferenceFragmentCompat。

还尝试按照 How to change text color of preference category in Android? 在首选项屏幕中使用布局标签,但未保存首选项。

class FragmentSettings: PreferenceFragmentCompat() {

    private lateinit var viewModel: SharedViewModel

    override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
        addPreferencesFromResource(R.xml.root_preferences)

        val application = requireNotNull(this.activity).application
        val dataBase = DataBase.getInstance(application)
        val repo = Repo(dataBase!!)

        viewModel = ViewModelProvider(this,
            SharedViewModelFactory(
                dataBase
            )
        ).get(SharedViewModel::class.java)

        (activity as MainActivity).supportActionBar?.title = "Settings"
}
            

这是我settingsPreference.xml中的代码。

<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:background="@color/colorExtra"
    android:backgroundTint="@color/colorExtra">

    <PreferenceCategory android:layout="@layout/pref_title" app:title="@string/location_header">

        <SwitchPreferenceCompat
            android:background="@color/colorExtra"
            android:backgroundTint="@color/colorExtra"
            app:defaultValue="true"
            android:layout= "@layout/switch_pref_item"
            app:disableDependentsState="true"
            app:key="USE_DEVICE_LOCATION"
            app:summary="Allow the app to get your location"
            app:title="@string/your_location_title" />

        <EditTextPreference
            android:background="@color/colorExtra"
            android:backgroundTint="@color/colorExtra"
            app:dependency="USE_DEVICE_LOCATION"
            app:key="setLocation"
            android:layout="@layout/set_location_pref"
            app:title="@string/set_location_title"
            app:useSimpleSummaryProvider="true" />


    </PreferenceCategory>

</PreferenceScreen>

这应该通过样式完成,并遵循用于设置任何布局样式的相同过程。它不是通过首选项 xml.

完成的

创建一个 xml 样式,它是 Theme.AppCompat 的子样式。然后您可以覆盖 android:windowBackgroundandroid:textColor 的颜色。您可以将此样式应用于清单中的 activity。

例如,在styles.xml中:

<color name="preferencesTextColor">$ff0000</color>
<color name="preferencesBackgroundColor">#202020</color>

<style name="MyPreferencesTheme" parent="Theme.AppCompat">
    <item name="android:textColor">@color/preferencesTextColor</item>
    <item name="android:windowBackground">@color/preferencesBackgroundColor</item>
</style>

然后在清单中,将主题应用到 activity:

<activity android:name="MyPreferencesActivity"
    android:theme="@style/MyPreferencesTheme"
    android:label="@string/myPreferenceActivityLabel" />