尝试执行看似有效的显式转换时发生ClassCastException

时间:2011-08-09 14:12:53

标签: android exception casting

我正在尝试构建这个简单的游戏,并且在尝试将我的SurfaceView投射到PuzzleSurfaceView(扩展SurfaceView)时,我一直遇到ClassCastException。

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) {

            }
        };

}
}

PuzzleSurfaceView类:

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 implements 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

}   
}

请指教......我几个小时以来一直撞在墙上......

我的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>

2 个答案:

答案 0 :(得分:1)

您需要实例化您的类并将其添加到布局中。你不能简单地施放。转换仅在转换为相同或父类或接口时有效。您也可以将其设为详细here的自定义组件,并在main.xml中使用PuzzleSurfaceView

答案 1 :(得分:0)

您必须将main.xml中的一行替换为以下内容:

 <com.scf.android.CAPuzzle.PuzzleSurfaceView android:layout_width="fill_parent"     android:layout_height="wrap_content" android:id="@+id/puzzleSurfaceView"></com.scf.android.CAPuzzle.PuzzleSurfaceView>

并添加构造函数

PuzzleSurfaceView(Context context, AttributeSet attrs)

在PuzzleSurfaceView课程中。