Android view.setBackgroundColor() from thread



我已经实现了一个游戏循环来处理SurfaceView,它运行良好,但是当缩小或移动画布时,它会在画布后面渲染缩放快照,这很烦人。

所以我想在onDraw()通话后清除我的视图背景。我尝试使用游戏循环或内部onDraw() view.setBackgroundColor(),但 android 声称我可以从另一个线程使用它。

有没有等效的方法可以做到这一点?

public class GameLoopThread extends Thread
{
    private MapView view;
    private boolean running = false;
    static final long FPS = 30;
    public GameLoopThread(MapView view)
    {   this.view = view;    }
    public void setRunning(boolean run)
    {   running = run;    }
    @Override
    public void run()
    {
        long ticksPS = 1000 / FPS;
        long startTime;
        long sleepTime;
        while (running)
        {
                Canvas c = null;
                startTime = System.currentTimeMillis();
                try
                {
                    c = view.getHolder().lockCanvas();
                    synchronized (view.getHolder())
                    {   
                        view.onDraw(c);
                        view.setBackgroundColor(Color.WHITE); // fails on this
                    }
                }
                finally
                {
                    if (c != null)
                        view.getHolder().unlockCanvasAndPost(c);
                }
                sleepTime = ticksPS - (System.currentTimeMillis() - startTime);
                try
                {
                    if (sleepTime > 0) sleep(sleepTime);
                    else sleep(10);
                }
                catch (Exception e){}
        }
    }
}

更新

我不想使用 view.setBackgroundColor(( 而是我想使用等效的东西来绘制画布

不能从单独的线程更新 UI,而是可以使用runOnUiThread

您只能从 UIThread "更改"视图。因此,一个可能的解决方案是通过您的Activity-Context和使用

activityContext.runOnUiThread

希望对你有帮助

这里最好使用 Handler,因为 GameLoopThread 没有上下文

android.os.Handler handler = new android.os.Handler();
        handler.post(new Runnable() {
            @Override
            public void run() {
                //update here
            }
        });

制作私人地图视图;到最后

您可以从

handlersasynctasksrunOnUIThread方法更新UI线程。您无法从普通线程执行此操作

感谢大家发布答案。

我找到了我的需求,这反过来又起到了setBackgroundColor()

作用

就像打电话给drawColor()一样简单

@Override
protected void onDraw(Canvas canvas)
{
    canvas.drawColor(Color.WHITE); // fill the whole canvas with white
    // rest of drawing
}

相关内容

最新更新