不调用surfaceCreated,因此线程无法启动

时间:2013-01-15 07:40:38

标签: android surfaceview

以下是我的简单代码,实际上我想重复在draw()方法中记录HELLO但是我的表面创建方法没有被调用,所以线程没有启动。请帮帮我

公共类MainActivity扩展了Activity {

private MyThread myThread ;
Panel _View;

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    _View = new Panel(this);
}

public class Panel extends SurfaceView implements SurfaceHolder.Callback {
    Canvas canvas;
    public Panel(Context context) {
        super(context);
        getHolder().addCallback(this);
    }//end of panel

    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
    }

    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        myThread= new MyThread(this);
        myThread.setRunning(true);
        myThread.start();   
    }

    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        myThread.setRunning(false); 
    }


    public void Draw(Canvas canvas){
        super.draw(canvas);
            this.canvas = canvas;   
            Log.d("HELLO", 0+"");
    }//end of DRAW()

}//end of Panel class

public class MyThread extends Thread {
    Panel panel;
    private SurfaceHolder myHolder;
    boolean mRun=false;

    public MyThread(Panel panel)
    {
        this.panel= panel;
        this.myHolder = panel.getHolder();
    }

    public void setRunning(boolean run){
        this.mRun=run;
    }

    public void run(){  
        Canvas canvas = null;
        while(mRun)
        {
            canvas=myHolder.lockCanvas();
            if(canvas!=null)
            {   
                panel.Draw(canvas);
            }
            myHolder.unlockCanvasAndPost(canvas);
        }
    }

}//MyThread class ends

} //鸟类狂热活动结束

1 个答案:

答案 0 :(得分:4)

在将表面添加到“视图”层次结构之前,不会创建表面。如果它是您唯一的View,则可以使用

进行设置
setContentView( _View);

在您的onCreate()方法中。