growse
growse

Reputation: 3752

How do you tint an androidx Preference icon?

I've got a drawable vector from the library that's defined with both a white foreground and a white tint:

<vector android:height="24dp" android:tint="#FFFFFF"
    android:viewportHeight="24" android:viewportWidth="24"
    android:width="24dp" xmlns:android="http://schemas.android.com/apk/res/android">
    <path android:fillColor="@android:color/white" android:pathData="M20,4L4,4c-1.1,0 -1.99,0.9 -1.99,2L2,18c0,1.1 0.9,2 2,2h16c1.1,0 2,-0.9 2,-2L22,6c0,-1.1 -0.9,-2 -2,-2zM20,8l-8,5 -8,-5L4,6l8,5 8,-5v2z"/>
</vector>

I'm trying to use this drawable as an icon on an androidx.preference element, but tint doesn't seem to be a property of the Preference class, and setting it doesn't do anything. The icon remains white.

<Preference
    app:icon="@drawable/ic_baseline_email_24"
    app:iconSpaceReserved="true"
    app:key="email"
    app:summary="@string/supportEmail"
    app:tint="@color/primary"
    app:title="Report an issue">
    <intent
        android:action="android.intent.action.SENDTO"
        android:data="@string/supportEmail" />
</Preference>

Is there a good way that allows me to tint icons on preferences?

Upvotes: 1

Views: 797

Answers (2)

tipapro
tipapro

Reputation: 1

Here is a solution that does not cause issues with tint in the toolbar. Invoke this in onViewCreated() of your PreferenceFragmentCompat.

val rv = view.findViewById<RecyclerView>(androidx.preference.R.id.recycler_view)
rv?.viewTreeObserver?.addOnDrawListener {
    rv.children.forEach { pref ->
        val icon = pref.findViewById<View>(android.R.id.icon) as? PreferenceImageView
        icon?.let {
            if (it.tag != "painted") {
                it.setColorFilter(
                    ContextCompat.getColor(requireContext(), R.color.iconColor),
                    PorterDuff.Mode.SRC_IN
                )
                it.tag = "painted"
            }
        }
    }
}

Upvotes: 0

Ashton Yoon
Ashton Yoon

Reputation: 192

https://github.com/Gericop/Android-Support-Preference-V7-Fix/issues/129#issuecomment-385314102

I found a better solution that only needs to be configured in style, and create values-night->color

<style name="AppTheme" parent="Theme.MaterialComponents.Light.NoActionBar">
    <item name="preferenceTheme">@style/PreferenceTheme</item>
</style>

<style name="PreferenceTheme" parent="@style/PreferenceThemeOverlay.v14.Material">
    <item name="android:tint">@color/pref_icon_color</item>
</style>

and add

    override fun onCreate(savedInstanceState: Bundle?) {
        delegate.setLocalNightMode(if (ThemeOverlayManager.isDarkTheme()) AppCompatDelegate.MODE_NIGHT_YES else AppCompatDelegate.MODE_NIGHT_NO)
        super.onCreate(savedInstanceState);
}

Use android:tint, app:tint is not working.

Upvotes: 4

Related Questions