我正在使用 PreferenceFragmentCompat,以下解决方案对我有用。
设置画面
import android.os.Bundle
import android.util.TypedValue
import android.view.View
import androidx.annotation.ColorInt
import androidx.preference.ListPreference
import androidx.preference.Preference
import androidx.preference.PreferenceFragmentCompat
import com.almarai.easypick.R
class SettingsScreen : PreferenceFragmentCompat(),
Preference.OnPreferenceChangeListener {
override fun onCreatePreferences(savedInstanceState: Bundle?, rootKey: String?) {
//Providing the XML file for the view to be created
setPreferencesFromResource(R.xml.app_settings_preferences, rootKey)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
//Get the Theme specific color
val typedValue = TypedValue()
val theme = requireContext().theme
/*R.attr.colorBackgroundScreenBody is my own attr from attrs.xml file,
you can directly use R.color.red - Or any color from your colors.xml
file if you do not have multi-theme app.*/
theme.resolveAttribute(R.attr.colorBackgroundScreenBody, typedValue, true)
@ColorInt val color = typedValue.data
view.setBackgroundColor(color)
super.onViewCreated(view, savedInstanceState)
}
}