好的,我自己找到了解决方案:

创建一个自定义的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:我得到了代码从查找开关位置 ,更改开关颜色在这里 ,谢谢!)

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐