java-函数返回后成员变量为null?

提问

我有一个扩展View的类.此类具有成员变量mCanvas

private Canvas mCanvas;

调整视图大小时将创建此变量,因此将设置画布的适当大小:

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    int curW = mBitmap != null ? mBitmap.getWidth() : 0;
    int curH = mBitmap != null ? mBitmap.getHeight() : 0;
    if (curW >= w && curH >= h) {
        return;
    }

    if (curW < w) curW = w;
    if (curH < h) curH = h;

    Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(canvasBitmap);
    if (mBitmap != null) {
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }
    mBitmap = canvasBitmap;
}

但是在我的onDraw函数中,当我尝试获取画布的宽度/高度时,出现了空指针异常.我不确定onSizeChanged何时真正被调用,我假设它总是在创建视图时(因此在onDraw之前)被调用.

但是,如果我的onDraw以此开始:

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        if(mCanvas == null)
        {
            Log.d("testing","mCanvas is null"
        }

当我到达onDraw时,logCat始终显示消息“ mCanvas为空”.

所以我更改了代码,以便当我在阅读onDraw时如果mCanvas为null,我将再次创建它:

private void resizeCanvas()
{
    int curW = mBitmap != null ? mBitmap.getWidth() : 0;
    int curH = mBitmap != null ? mBitmap.getHeight() : 0;

    if (curW >= this.getWidth() && curH >= this.getHeight()) {
        return;
    }

    if (curW < this.getWidth()) curW = this.getWidth();
    if (curH < this.getHeight()) curH = this.getHeight();

    Bitmap canvasBitmap = Bitmap.createBitmap(curW, curH, Bitmap.Config.ARGB_8888);
    mCanvas = new Canvas(canvasBitmap);

    if (mBitmap != null) {
        mCanvas.drawBitmap(mBitmap, 0, 0, null);
    }

    mBitmap = canvasBitmap;
}

@Override
protected void onDraw(Canvas canvas) {
    if (mBitmap != null) {
        if(mCanvas == null)
        {
            resizeCanvas();
            if(mCanvas == null)
            {
                Log.d("test","canvas is still null");
            }

logCat仍然打印“画布仍然为空”

有人可以解释这里发生了什么吗?我对android很陌生,大部分代码来自我一直在玩的touchpaint示例.

如果我在mCanvas为null的情况下检查resizeCanvas函数内部,则始终表示它不为null.但是,如果我在调用该函数后立即检查,则始终为null.

最佳答案

我认为问题出在您的resizeCanvas中,因为您可以在初始化mCanvas之前从中返回.
评论