0

我创建了一个自定义开关,并在片段中使用它。但我收到以下错误:

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

我正在使用的自定义开关是:

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);
    }
}

布局文件中的开关是;

<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" />

有人可以帮我解决这个问题吗?谢谢

4

1 回答 1

2

您需要实现一个接受 aContext和的构造函数AttributeSet。您可以将实现委托给 3-arg 构造函数:

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

堆栈跟踪中的<init>是指对象初始化,即构造函数。

于 2013-12-30T12:28:38.527 回答