SurfaceView无法实例化

时间:2013-09-20 11:06:30

标签: android surfaceview

我正在尝试在我的activity的XML文件中实现自定义SurfaceView,然后在活动的代码中引用它以进行绘制等。但是,我收到以下错误:

The following classes could not be instantiated:
- com.example.animateddrawable.MainActivity.DrawingPanel 

MainActivity Code:

package com.example.animateddrawable;

import java.util.Timer;
import java.util.TimerTask;

import android.app.Activity;
import android.content.Context;
...


com.example.animateddrawable.MainActivity.DrawingPanel.PanelThread;


public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    dp = new DrawingPanel(this, null);
    setContentView(R.layout.activity_main);

    }

    public class DrawingPanel extends SurfaceView implements SurfaceHolder.Callback {
        public DrawingPanel( Context context, AttributeSet attributeSet){
        super(context, attributeSet);
        init();
    }

    public void init(){
        getHolder().addCallback(this);
    }

    }
}

XML代码     

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <com.example.animateddrawable.MainActivity.DrawingPanel
            android:id="@+id/surfaceView"
            android:layout_width = "fill_parent"
            android:layout_height = "fill_parent"/>

    </FrameLayout>

</LinearLayout>

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_weight="1" >
</LinearLayout>

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试添加如下构造函数:

public DrawingPanel(Context context) {
    super(context);
    getHolder().addCallback(this);
}
public DrawingPanel(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    getHolder().addCallback(this);
}

将此添加到您的其他构造函数中:

 getHolder().addCallback(this);