绘制/布局期间的对象分配?

lra*_*s15 16 java android

在绘制/布局期间,我得到3个对象分配警告

super.onDraw(canvas);
canvas.drawColor(Color.WHITE);
Paint textPaint = new Paint();
textPaint.setARGB(50,100,100,250);
textPaint.setTextAlign(Align.CENTER);
textPaint.setTextSize(50);
textPaint.setTypeface(font);
canvas.drawText("Logan is awesom",canvas.getWidth()/2,200,textPaint);
canvas.drawBitmap(pBall, (canvas.getWidth()/2), changingY, null);
if (changingY <canvas.getHeight()){
changingY += 10;
}else{
changingY=0;
}
Rect middleRect = new Rect();
middleRect.set(0, 400, canvas.getWidth(), 550);
Paint ourBlue = new Paint();
ourBlue.setColor(Color.BLUE);
canvas.drawRect(middleRect, ourBlue);
Run Code Online (Sandbox Code Playgroud)

我在新的Rect()上遇到错误; 并在新的Paint();

确切的错误是在绘制/布局操作期间避免对象分配(预定位和重用)

Pav*_*dka 24

那么,你的'错误'指向确切的问题.onDraw()操作系统多次调用方法,因此在此函数中分配内容是非常糟糕的主意.您需要事先分配您的内容RectPaint在内部使用它们onDraw

class YourClass extends View
{
    Rect middleRect;
    Paint ourBlue;
    Paint textPaint;

    public YourClass()
    {
         //constructor
         init();
    }

    private void init()
    {
        middleRect = new Rect();
        ourBlue; = new Paint();
        textPaint = new Paint();

        ourBlue.setColor(Color.BLUE);
        textPaint.setARGB(50,100,100,250);
        textPaint.setTextAlign(Align.CENTER);
        textPaint.setTextSize(50);
        textPaint.setTypeface(font);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        canvas.drawColor(Color.WHITE);

        canvas.drawText("Logan is awesom",canvas.getWidth()/2,200,textPaint);
        canvas.drawBitmap(pBall, (canvas.getWidth()/2), changingY, null);
        if (changingY <canvas.getHeight()){
            changingY += 10;
        }else{
            changingY=0;
        }

        //if canvas size doesn't change - this can be moved to init() as well
        middleRect.set(0, 400, canvas.getWidth(), 550);

        canvas.drawRect(middleRect, ourBlue);
    }
}
Run Code Online (Sandbox Code Playgroud)