android 自定义switchpreference,android - Android-如何动态更改SwitchPreference开关的拇指/轨道颜色 - 堆栈内存溢出...
好的,我自己找到了解决方案:创建一个自定义的SwitchPreference类,然后将其应用于您获得的所有SwitchPreference小部件,该类如下所示:class ColorSwitchPreference extends SwitchPreference {Switch aSwitch;SharedPreferences sharedPreferences;public ColorSwi
好的,我自己找到了解决方案:
创建一个自定义的SwitchPreference类,然后将其应用于您获得的所有SwitchPreference小部件,该类如下所示:
class ColorSwitchPreference extends SwitchPreference {
Switch aSwitch;
SharedPreferences sharedPreferences;
public ColorSwitchPreference(Context context){
super(context);
}
public ColorSwitchPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public ColorSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public ColorSwitchPreference(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
aSwitch = findSwitchInChildViews((ViewGroup) view);
if (aSwitch!=null) {
//do change color here
changeColor(aSwitch.isChecked(),aSwitch.isEnabled());
aSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
changeColor(isChecked, aSwitch.isEnabled());
}
});
}
}
private void changeColor(boolean checked, boolean enabled){
try {
sharedPreferences = getContext().getSharedPreferences("settings_data",MODE_PRIVATE);
//apply the colors here
int thumbCheckedColor = sharedPreferences.getInt("theme_color_key",Color.parseColor("#3F51B5"));
int thumbUncheckedColor = Color.parseColor("#ECECEC");
int trackCheckedColor = sharedPreferences.getInt("theme_color_key",Color.parseColor("#3F51B5"));
int trackUncheckedColor = Color.parseColor("#B9B9B9");
if(enabled){
aSwitch.getThumbDrawable().setColorFilter(checked ? thumbCheckedColor : thumbUncheckedColor, PorterDuff.Mode.MULTIPLY);
aSwitch.getTrackDrawable().setColorFilter(checked ? trackCheckedColor : trackUncheckedColor, PorterDuff.Mode.MULTIPLY);
}else {
aSwitch.getThumbDrawable().setColorFilter(Color.parseColor("#B9B9B9"), PorterDuff.Mode.MULTIPLY);
aSwitch.getTrackDrawable().setColorFilter(Color.parseColor("#E9E9E9"), PorterDuff.Mode.MULTIPLY);
}
}catch (NullPointerException e){
e.printStackTrace();
}
}
private Switch findSwitchInChildViews(ViewGroup view) {// find the Switch widget in the SwitchPreference
for (int i=0;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;
}
}
基本上,您可以使用findSwitchInChildViews()在SwitchPreference中获取Switch小部件,然后从那里更改颜色。
而已! 这实际上是一种非常简单的方法,但是我之前从未考虑过,希望这篇文章可以在以后帮助某人避免我的挣扎。
(PS:我得到了代码从查找开关位置 ,更改开关颜色在这里 ,谢谢!)
更多推荐
所有评论(0)