android - SwitchPreferenceCompat 的自定义样式属性(支持 v7)

标签 android android-preferences preferencefragment

enter image description here

我正在尝试在 SwitchPreferenceCompat 的顶部添加一些空间它位于 PreferenceFragmentCompat 的内部。基本上我只需要它和顶部之间有一些空间 Toolbar ,通过扩展其高度或使用填充间隙而不添加空白,否则会干扰 Toolbar 的高程阴影。我相信我可以通过向 SwitchPreferenceCompat 添加自定义样式来实现此目的,但我很难让它发挥作用。

这是我尝试过的:

在我的styles.xml -

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

在我的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" />

我认为我只是没有正确覆盖样式,但我无法找到如何使用 SwitchPreferenceCompat 来做到这一点。预先感谢您!

最佳答案

我知道这已经晚了,但我从以下代码中得到结果:

我的应用主题:

<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>

我喜欢的主题:

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

在我的 PreferenceSwitchCompat 中,我使用了布局属性,您应该为您的 View 创建新布局

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

您必须在此处自定义 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"/>

希望对别人有帮助。

关于android - SwitchPreferenceCompat 的自定义样式属性(支持 v7),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41352078/

相关文章:

Android - ListView - 默认列表项(状态)背景颜色

java - 必须释放分数忍者才能保存分数吗?

android - findViewById 在 PreferenceFragment 的 onViewCreated 中失败,Android

android - 将数据从 onSharedPreferenceChanged() 发送到另一个 UI Fragment

android - 没有 radio 的 ListPreference

java - PreferenceFragmentCompat 不显示

android - (Activity+preferencefragment) 错误膨胀类 com.android.internal.widget.ActionBarContainer

android - 调用从 Android/Java 返回值的 Unity C# 方法

android - 运行此 AVD 需要 KVM。未知错误!请提交针对 Android Studio 的错误

android - SharedPreferences.getInt() 导致 ClassCastException - 为什么?