Custom style attributes for SwitchPreferenceCompat (support v7)

2k views Asked by At

enter image description here

I am trying to add some space to the the top of my SwitchPreferenceCompat which is inside of a PreferenceFragmentCompat. Basically I just need some room between it and the top Toolbar, either by expanding its height or with a padding gap without adding a white space that will interfere with the elevation shadow of the Toolbar. I believe I can achieve this by adding a custom style to the SwitchPreferenceCompat, but I am having trouble getting that to work.

Here is what I have tried:

In my styles.xml-

<style name="SwitchPreferenceNew" parent="Preference.SwitchPreferenceCompat.Material">
    <item name="android:paddingTop">20dp</item>
</style>

In my app_preferences.xml-

<android.support.v7.preference.SwitchPreferenceCompat
    style="@style/SwitchPreferenceNew"
    android:defaultValue="false"
    android:icon="@drawable/ic_power_settings_new_black_48dp"
    android:key="prefsActivate"
    android:summary=""
    android:title="Activate reminders" />

I think I am just not overriding the style correctly, but I am having trouble finding out how to do it with the SwitchPreferenceCompat. Thank you in advance!

1

There are 1 answers

0
naser khsoravi On BEST ANSWER

I know this is late but i get result from following code:

my app theme:

<style name="AppTheme" parent="Theme.AppCompat.NoActionBar">
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
    <item name="preferenceTheme">@style/my_preference_theme</item>
</style>

my preference theme:

<style name="my_preference_theme" parent="@style/PreferenceThemeOverlay">
    <item name="switchPreferenceCompatStyle">@style/preference_switch_compat</item>
</style>

in my PreferenceSwitchCompat i used layout property and you should create new layout for your view

<style name="preference_switch_compat">
    <item name="android:layout">@layout/switch_layout</item>
</style>

this is here you must customize your view:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.SwitchCompat
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/switchWidget"
    android:background="#f00"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"/>

hope to help to someone.