Butter Knife 和 Material 设计库的使用

Butter Knife and Material Design Library usage

我在我的项目中使用 Butter Knife 以及 UI 的 Material 设计库。

尝试使用 Material 设计库创建按钮时,由于使用了 Butter Knife,我得到了一个 'Class Cast Exception'。

有办法解决这个问题吗?

MainActivity.Java

@Bind(R.id.switch1) Switch switch;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    ButterKnife.bind(this);
}

XML 切换布局

<com.gc.materialdesign.views.Switch
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/switch1"
    android:layout_centerHorizontal="true" />

错误

Caused by: java.lang.RuntimeException: Unable to bind views for com.example.MainActivty

Caused by: java.lang.ClassCastException:com.gc.materialdesign.views.Switch cannot be cast to android.widget.Switch

您正在导入错误的 Switch - 而不是导入 android.widget.Switch,您需要导入 com.gc.materialdesign.views.Switch 并在定义 switch 时使用 class变量。

删除行

import android.widget.Switch;

并将其替换为

import com.gc.materialdesign.views.Switch;

您只是选择了导入错误 Switch class.