我有一个自定义开关控制类MySwitch
public class MySwitch extends RelativeLayout implements CompoundButton.OnCheckedChangeListener {
//private final Context context;
private String swKey;
private Integer swIcoOn, swIcoOff;
Switch mySW;
ImageView swIco;
SharedPreferences preferences;
public MySwitch(Context context) {
super(context, null);
}
public MySwitch(Context context, AttributeSet attrs) {
this(context, attrs, R.layout.my_switch);
}
public MySwitch(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
preferences = PreferenceManager.getDefaultSharedPreferences(context);
LayoutInflater.from(context).inflate(defStyleAttr, this, true);
//View.inflate(context, defStyleAttr, this);
swIco = (ImageView) findViewById(R.id.swIcon);
TextView myText = (TextView) findViewById(R.id.swTitle);
TextView mySummary = (TextView) findViewById(R.id.swSummary);
mySW = (Switch) findViewById(R.id.mySW);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MySwitch, 0, 0);
try {
myText.setText(ta.getString(R.styleable.MySwitch_android_title));
mySummary.setText(ta.getString(R.styleable.MySwitch_android_summary));
mySW.setTextOn(ta.getString(R.styleable.MySwitch_android_switchTextOn));
mySW.setTextOff(ta.getString(R.styleable.MySwitch_android_switchTextOff));
mySW.setOnCheckedChangeListener(this);
swIcoOn = ta.getResourceId(R.styleable.MySwitch_icoOn, 0);
swIcoOff = ta.getResourceId(R.styleable.MySwitch_icoOff, 0);
swKey = ta.getString(R.styleable.MySwitch_android_key);
update();
} finally {
ta.recycle();
}
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
update(b);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean(swKey, b);
editor.commit();
}
public void update(Boolean val) {
mySW.setChecked(val);
if(val)
swIco.setImageResource(swIcoOn);
else
swIco.setImageResource(swIcoOff);
}
public void update() {
update(preferences.getBoolean(swKey, false));
}
}
我想在SwitchPreference中重用此类中的代码,因为代码几乎相同,所以它的类是
public class MySwitchPref extends SwitchPreference{
MySwitch obj;
private SharedPreferences preferences;
public MySwitchPref(Context context, AttributeSet attrs) {
super(context, attrs);
//setLayoutResource(R.layout.my_switch);
obj = new MySwitch(context,attrs);
}
@Override
protected void onBindView(View view) {
super.onBindView(view);
obj.update();
}
}
问题是在SwitchPreference上没有显示图标。 如何才能在SwitchPreference中显示图标?