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

holder.getSurface().isValid() is returning false

我正在使用 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);
    }
}

}

您必须在 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());

请试试这个。我想它会对你有所帮助