ClassCastException occurs when trying to perform a seemingly valid explicit cast
I'm trying to build this simple game, and I keep encountering a ClassCastException when trying to cast my my SurfaceView into a PuzzleSurfaceView (which extends SurfaceView).
package com.scf.android.CAPuzzle;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
public class CAPuzzleActivity extends Activity {
PuzzleSurfaceView puzzleSurfaceView;
View.OnClickListener puzzleClickListener;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
puzzleSurfaceView = (PuzzleSurfaceView)findViewById(R.id.puzzleSurfaceView);
puzzleClickListener = new View.OnClickListener() {
public void onClick(View v) {
}
};
}
}
And the PuzzleSurfaceView class:
package com.scf.android.CAPuzzle;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
class PuzzleSurfaceView extends SurfaceView implemen开发者_运维技巧ts SurfaceHolder.Callback {
Bitmap live;
Bitmap dead;
public PuzzleSurfaceView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
@Override
public void onDraw(Canvas c) {
c.drawBitmap(live, 0, 0, null);
}
@Override
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder arg0) {
// TODO Auto-generated method stub
live = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
}
@Override
public void surfaceDestroyed(SurfaceHolder arg0) {
// TODO Auto-generated method stub
}
}
Please advise... I've been banging my head against the wall for hours now...
My main.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"
>
<SurfaceView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/puzzleSurfaceView"></SurfaceView>
<SurfaceView android:layout_height="wrap_content" android:layout_width="fill_parent" android:id="@+id/solutionSurfaceView"></SurfaceView>
</LinearLayout>
You will need to instantiate your class and add it to the layout. You can't simply cast. Casting only works when casting to the same or parent classes or interfaces. You could also make it a custom component as detailed here and use your PuzzleSurfaceView in your main.xml
You must replace one row in main.xml to following:
<com.scf.android.CAPuzzle.PuzzleSurfaceView android:layout_width="fill_parent" android:layout_height="wrap_content" android:id="@+id/puzzleSurfaceView"></com.scf.android.CAPuzzle.PuzzleSurfaceView>
and add constructor
PuzzleSurfaceView(Context context, AttributeSet attrs)
at your PuzzleSurfaceView class.
精彩评论