3
我有一個擴展視圖的類。這個類有成員變量mCanvas函數返回後成員變量爲null?
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"
}
logcat中始終顯示消息 「mCanvas爲空」 當我到達的onDraw。
所以我改變了代碼,這樣,如果mCanvas爲空,當我讀到的onDraw我只是重新創建:
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示例。
如果我檢查裏面的resizeCanvas函數,如果mCanvas爲null它總是說它不是null。但是如果我在調用該函數後檢查它總是空的。