[英]android - cast ToggleButton to subclass
I might be misunderstanding type casting, but here is my problem. 我可能会误解类型转换,但这是我的问题。
I've got an Android View with a ToggleButton: 我有一个带有ToggleButton的Android视图:
<LinearLayout
... >
<ToggleButton
android:id="@+id/btnRec"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:textOff="Start TEST"
android:textOn="Stop TEST" />
...
</LinearLayout>
Then in my activity I declare a ToggleButton variable: 然后在我的活动中,声明一个ToggleButton变量:
private ToggleButton mRecordButton = null;
Now, I implement a subclass of ToggleButton, called RecordButton: 现在,我实现了ToggleButton的子类,称为RecordButton:
class RecordButton extends ToggleButton {
OnCheckedChangeListener clicker = new OnCheckedChangeListener() {
...
};
public RecordButton(Context ctx) {
super(ctx);
setOnCheckedChangeListener(clicker);
}
}
And finally in onCreate
I find the button by its id: 最后在
onCreate
我通过其ID找到了按钮:
mRecordButton = (RecordButton) findViewById(R.id.btnRec);
This throws a ClassCastException
. 这将引发
ClassCastException
。
Why? 为什么? How can I cast it to
RecordButton
(the subclass) from ToggleButton
(the superclass)? 如何将其从
ToggleButton
(超类)转换为RecordButton
(子类)?
in your XML, replace the regular ToogleButton
with the custom one.. 在您的XML中,用自定义
ToogleButton
替换常规的ToogleButton
。
<LinearLayout
... >
<package.class.RecordButton
android:id="@+id/btnRec"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:textOff="Start TEST"
android:textOn="Stop TEST" />
...
You can use your views in layout: 您可以在布局中使用视图:
<LinearLayout
... >
<com.project.RecordButton
android:id="@+id/btnRec"
android:layout_width="125dp"
android:layout_height="wrap_content"
android:textOff="Start TEST"
android:textOn="Stop TEST" />
...
</LinearLayout>
Eclipse with android SDK can automatically determine your views: 带有android SDK的Eclipse可以自动确定您的视图:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.