gpt4 book ai didi

java - 自定义布局中 switchpreference 中开/关切换的颜色变化

转载 作者:行者123 更新时间:2023-11-30 02:27:48 24 4
gpt4 key购买 nike

我在自定义布局中使用 PreferenceScreen 开发了一个设置页面。有一个 switchpreference 我想改变颜色。目前它采用默认颜色。但是我想在用户打开和关闭它时更改它的颜色。当用户打开时,打开的一侧应该是红色,当用户切换到关闭的一侧时,它的“关闭”一侧应该是浅灰色。我的 Switchpreference 代码如下:

<?xml version="1.0" encoding="utf-8"?>

<PreferenceCategory android:key="pref" >

<SwitchPreference
android:key="switchbutton"
android:summaryOff="OFF"
android:summaryOn="ON"
android:title="start" />
</PreferenceCategory>

我是 android 编程的新手,所以请合作。如果有人帮助我,我将很高兴。提前致谢!

最佳答案

我在 Custom SwitchPreference in Android 的类似问题中发布了这个答案

实现此目的的一种方法是子类化 SwitchPreference 并覆盖 onBindView 方法。这样做时,您仍然希望在该方法中调用 super.onBindView(view),但随后在 subview 中找到 Switch 并根据需要设置样式:

package com.example;

import android.annotation.SuppressLint;
import android.content.Context;
import android.preference.SwitchPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Switch;

import com.example.R;


public class CustomSwitchPreference extends SwitchPreference {

@SuppressLint("NewApi")
public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}

public CustomSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}

public CustomSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}

public CustomSwitchPreference(Context context) {
super(context);
}

@Override
protected void onBindView(View view) {

super.onBindView(view);
Switch theSwitch = findSwitchInChildviews((ViewGroup) view);
if (theSwitch!=null) {
//do styling here
theSwitch.setThumbResource(R.drawable.new_thumb_resource);
}

}

private Switch findSwitchInChildviews(ViewGroup view) {
for (int i=0;i<view.getChildCount();i++) {
View thisChildview = view.getChildAt(i);
if (thisChildview instanceof Switch) {
return (Switch)thisChildview;
}
else if (thisChildview instanceof ViewGroup) {
Switch theSwitch = findSwitchInChildviews((ViewGroup) thisChildview);
if (theSwitch!=null) return theSwitch;
}
}
return null;
}
}

关于java - 自定义布局中 switchpreference 中开/关切换的颜色变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27704028/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com