我尝试在 android 中获得自定义开关首选项。这是我的代码
switch_widget.xml
<Switch xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/customswitch"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:clickable="false"
/>
preference xml file :
<com.tnavitech.utils.CustomSwitch
android:title="Hide app icon"
android:key="hideicon"
android:defaultValue="false"
android:disableDependentsState="true"
android:widgetLayout="@layout/switch_widget"
/>
然后我扩展“SwitchPreference”,并在“onBindView”类中,并在 OnPreferenceChangeListener 中处理开关状态:
public class CustomSwitch extends SwitchPreference {
Switch swit;
public CustomCheckbox(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected void onBindView(final View rootView) {
ViewGroup viewGroup= (ViewGroup)rootView;
super.onBindView(rootView);
if(swit==null){
swit = (Switch) rootView.findViewById(R.id.customswitch);
}
this.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference arg0, Object arg1) {
if (arg1 instanceof Boolean) {
Boolean enabled = (Boolean) arg1;
if(enabled){
swit.setChecked(true); /// cant toggle switch here
Toast.makeText(getContext(), "on", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext(), "off", Toast.LENGTH_SHORT).show();
swit.setSelected(false); ///cant toggle switch here
}
}
return true;
}
});
}
在 setOnPreferenceChangeListener 中,我无法打开或关闭开关。我怎么能解决这个问题?谢谢!