如何解决将自定义视图放置在另一个中时我在 Eclipse 设计器中遇到的异常。
java.lang.ClassCastException: com.fitness.app.Stopper cannot be cast to android.widget.Button at com.fitness.app.Stopper.<init>(Stopper.java:25).
com.fitness.app.Stopper XML:
<merge xmlns:android="http://schemas.android.com/apk/res/android" >
<Button
android:id="@+id/btnStartStopper"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="25dp"
android:text="Start"
/>
<Chronometer
android:id="@+id/chronometer1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="@+id/btnStartStopper"
android:layout_marginLeft="18dp"
android:layout_toRightOf="@+id/btnStartStopper"
android:text="Chronometer"
android:textSize="45sp" />
</merge>
和 com.fitness.app.Stopper 第 25 行来自错误:
Button btnStart = (Button) findViewById(R.id.btnStartStopper);
public class Stopper extends LinearLayout {
private Chronometer stopper;
private boolean stopper_started = false;
public Stopper(Context context)
{
super(context);
}
public Stopper(Context context, AttributeSet attrs) {
super(context, attrs);
initializeLayoutBasics(context);
this.stopper = (Chronometer) findViewById(R.id.chronometer1);
Button btnStart = (Button) findViewById(R.id.btnStartStopper);
btnStart.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
startOrStopStopper(arg0);
}
});
}
private void initializeLayoutBasics(Context context) {
setOrientation(HORIZONTAL);
final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
inflater.inflate(R.layout.fragment_stopper, this, true);//TODO change name fragment to different
}
public void startOrStopStopper(View v)
{
if(!stopper_started)
stopper.start();
else
stopper.stop();
stopper_started = !stopper_started;
}
}