holder.getSurface()。isValid()返回false

时间:2017-12-06 07:36:15

标签: android surfaceholder

我正在使用Surfaceview来更改背景图像。但是我在holder.getSurface()。isValid()上得到了错误,我不知道为什么。我在这里查看了一些类似的问题,但仍然无法解决。到目前为止我做了什么,或者还有其他什么我应该尝试

由于

import android.content.Context;

import android.graphics.BitmapFactory;
import android.graphics.Canvas;

import android.view.SurfaceHolder;
import android.view.SurfaceView;


public class BrickSmasherView extends SurfaceView {



    SurfaceHolder holder;




    Canvas canvas;
    Context context;

    Thread back = null;

    volatile boolean running = false;

    public BrickSmasherView(Context context) {
        super(context);
        this.context = context;
        holder = getHolder();

    }
    public void runbackThread(){
        back = new Thread(new Runnable() {
            @Override
            public void run() {
                while (running){
                    draw();
                }
            }
        });
        back.start();
    }




    public  void resumegame(){
        running = true;
       runbackThread();

    }

    public void pausegame(){

        running = false;
        try
        {
            back.join();


        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

public void  draw(){
    if(holder.getSurface().isValid()){
        canvas = holder.lockCanvas();
        canvas.drawBitmap(BitmapFactory.decodeResource(getResources(),R.drawable.sky),0,0,null);
        holder.unlockCanvasAndPost(canvas);
    }
}

}

1 个答案:

答案 0 :(得分:0)

您必须在SurfaceView中添加Callback以接收有关Surface可用性的事件,并从线程中进行绘制。

回调示例如下所示:

public class MyCallback implements SurfaceHolder.Callback {
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, 
        int width, int height) {    
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // you need to start your drawing thread here
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {  
        // and here you need to stop it
    }
}

而且您需要将此回调设置为SurfaceHolder:

surface.getHolder().addCallback(new MyCallback());

请试试这个。我认为它会帮助你