Error inflating custom Switch class: Android

804 views Asked by At

I have created a custom switch and I am using that in a fragment. But i am getting the following error:

12-30 17:46:55.456: E/AndroidRuntime(13351): android.view.InflateException: Binary XML file line #47: Error inflating class com.arrayent.arrayentcesdemo.customview.CustomSwitch

12-30 17:46:55.456: E/AndroidRuntime(13351): Caused by: java.lang.NoSuchMethodException: <init> [class android.content.Context, interface android.util.Att

The custom switch that i am using is:

import android.content.Context;
import android.util.AttributeSet;
import android.widget.CompoundButton;
import android.widget.Switch;

public class CustomSwitch extends Switch {
    public CustomSwitch(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    private CompoundButton.OnCheckedChangeListener myListener = null;

    @Override
    public void setOnCheckedChangeListener(
            CompoundButton.OnCheckedChangeListener listener) {
        if (this.myListener == null)
            this.myListener = listener;
        super.setOnCheckedChangeListener(listener);
    }

    public void silentlySetChecked(boolean checked) {
        toggleListener(false);
        super.setChecked(checked);
        toggleListener(true);
    }

    private void toggleListener(boolean on) {
        if (on) {
            this.setOnCheckedChangeListener(myListener);
        } else
            this.setOnCheckedChangeListener(null);
    }
}

And the switch in the layout file is;

<com.arrayent.arrayentcesdemo.customview.CustomSwitch
        android:id="@+id/light_switch"
        android:layout_width="100dip"
        android:layout_height="5dip"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="50dip"
        android:scaleY="0.7"
        android:textOff="       "
        android:textOn="       "
        android:thumb="@drawable/plug_thumb_bitmap"
        android:track="@drawable/btntoggle_selector_light" />

Could someone please help me figure this out? Thanks

1

There are 1 answers

2
laalto On

You need to implement a constructor that takes in a Context and AttributeSet. You can delegate the implementation to the 3-arg constructor:

public CustomSwitch(Context context, AttributeSet attrs) {
    this(context, attrs, null);
}

The <init> in the stack trace refers to object initialization, i.e. constructor.