androidandroid-layoutandroid-preferencesandroid-settings

Change Background of SwitchPreferenceCompat


i am tring to create a settings screen using androidx.preference.PreferenceScreen.

<androidx.preference.PreferenceScreen
xmlns:app="http://schemas.android.com/apk/res-auto">

<SwitchPreferenceCompat
    app:key="enable"
    app:title="@string/sync_title"/>

<SwitchPreferenceCompat
    app:key="missed"
    app:summary="Remove missed calls and block unwanted ones"
    app:dependency="enable"
    app:title="Missed call alert" />

<SwitchPreferenceCompat
    app:key="blocked"
    app:dependency="enable"
    app:summary="Receive a silent notification when you receive an unwanted call"
    app:title="Be informed of blocked calls " />


<PreferenceCategory
    app:key="premium_cat"
    app:dependency="enable"
    app:title="Premium">


    <SwitchPreferenceCompat
        app:key="premium"
        app:dependency="enable"
        app:summary="Automatically identify spam calls"
        app:title="Real time call alert" />

</PreferenceCategory>

the problem i have is the i want to add a different background color for the first settings

<SwitchPreferenceCompat
app:key="enable"
app:title="@string/sync_title"/>

i tried adding a layout but it does not work all it does is hide the SwitchPreferenceCompat


Solution

  • You can do it like this

    Create a new java class extended from SwitchPreferenceCompat

    public class MySwitchPreference extends SwitchPreference {
    
        public MySwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) 
        {
            super(context, attrs, defStyleAttr);
        }
    
        public MySwitchPreference(Context context, AttributeSet attrs) {
            super(context, attrs);
        }
    
        public MySwitchPreference(Context context) {
            super(context);
        }
    
        @Override
        protected void onBindView(View view) {
            super.onBindView(view);
            view.setBackgroundResource(R.color.your_color); // put here the color defined in colors.xml
        }
    }
    

    Then, use it like this

    <com.your_package.your_name.MySwitchPreferenceCompat
        app:key="enable"
        app:title="@string/sync_title"/>
    

    UPDATE: It seems like onBindView isn't used by SwitchPreferenceCompat anymore. Now I implemented it like this in Kotlin:

    internal class MySwitchPreference : SwitchPreferenceCompat {
    
    constructor(context: Context?, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {}
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs) {}
    constructor(context: Context?) : super(context) {}
    
    
    override fun onBindViewHolder(holder: PreferenceViewHolder?) {
        super.onBindViewHolder(holder)
        holder?.itemView?.let { view ->
                view.setBackgroundResource(R.color.your_color)
        }
    }
    

    }