【发布时间】:2011-11-27 16:08:43
【问题描述】:
我在使用自定义 Button 类时遇到问题。
我尝试将 xml 布局从 <Button/> 更改为 <gButton/>,但没有成功。
我也尝试过在第 15 行投射 Button page1 = (gButton) findView....,但由于某种原因不起作用(你可以投射子类,对吗?)
我不断从 LogCat 得到的错误是:
Caused by: java.lang.ClassCastException: android.widget.Button
at flash.tut.ButtonPage.onCreate(ButtonPage.java:15)
非常感谢任何帮助。
这是我的按钮视图:
public class ButtonPage extends Activity{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.button);
gButton page1 = (gButton) findViewById(R.id.Button01); //<---LogCat: ClassCastException
page1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent mI = new Intent(view.getContext(), Page1.class);
startActivityForResult(mI, 0);
}
});
}
}
还有我的 gButton 扩展了按钮类:
public class gButton extends Button{
private static Context con;
public gButton(){this("Blank");}
public gButton(String name){
this(name, R.color.text_color);
}
public gButton(String name, int col) {
this(name, col, con);
}
public gButton(String name, int col, Context context) {
super(context); //necessary context...dont know why.
setBackgroundResource(R.drawable.icon);
setTextColor(col);
setText(name);
setTextSize(14);
}
}
最后是我的 xml 布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Page 1"
android:id="@+id/Button01"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="Page 2"
android:id="@+id/Button02"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="Page 3"
android:id="@+id/Button03"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
<Button android:text="ListView Page"
android:id="@+id/ButtonList"
android:layout_width="250px"
android:textSize="18px"
android:layout_height="55px">
</Button>
</LinearLayout>
【问题讨论】:
标签: java android classcastexception inheritance