OK,我發現我自己的解決方案:
創建一個自定義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.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;
}
}
基本上,您使用findSwitchInChildViews()
獲取SwitchPreference中的Switch小部件,然後從那裏更改顏色。
就是這樣!這實際上是一個非常簡單的方法,但我之前沒有考慮過,希望這篇文章能夠幫助未來的某個人避免我的掙扎。
(PS:我得到了代碼從here查找開關,從here改變開關顏色,謝謝)
請參閱本https://stackoverflow.com/questions/21235829/custom-switchpreference-in-android – Gautam
Gautam,我已經嘗試過自定義switchpreference,問題是我不知道如何在我的Java代碼中設置開關的拇指/軌道的顏色。 – jackz314