函数返回后,成员变量是否为空?

时间:2012-02-26 16:20:53

标签: java android

我有一个扩展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为null。

所以我更改了代码,以便当我读取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仍会打印“canvas仍然为null”

有人可以解释这里发生了什么吗?我是android的新手,大部分代码来自我一直在玩的触控笔示例。

如果我检查resizeCanvas函数内部,如果mCanvas为null,它总是说它不是null。但是,如果我在调用该函数后立即检查它,它总是为空。

1 个答案:

答案 0 :(得分:4)

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