I try to get custom switch preference in adroid. Here is my code
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"
/>
Then I extend "SwitchPreference", and in "onBindView" class, and handle switch states in 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;
}
});
}
In setOnPreferenceChangeListener i cant toggle the swith on or off. How could I solve this? Thanks!