更改SwitchPreferenceCompat

时间:2019-06-23 01:58:38

标签: android android-studio android-layout android-preferences android-settings

我正准备使用 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>

我遇到的问题是我想为第一个设置添加不同的背景颜色

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

我尝试添加布局,但它无法正常工作,只是隐藏了 SwitchPreferenceCompat

1 个答案:

答案 0 :(得分:2)

您可以这样做

创建一个从SwitchPreferenceCompat扩展的新Java类

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

然后,像这样使用它

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