成员变量是在函数返回空? [英] member variable is null after function return?
问题描述
我有一个扩展视图类。这个类有成员变量mCanvas
I have a class that extends View. This class has the member variable mCanvas
private Canvas mCanvas;
视图时大小创建此变量,所以适当的大小画布设置:
This variable is created when the view is resized, so the appropriate sizes for the canvas are set:
@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。当它总是会被调用
But in my onDraw function i'm getting a null pointer exception when i try get the width/height of my canvas. I was unsure when onSizeChanged is actually getting called, i was assuming it would always get called when the view was created and therefore before onDraw.
但是,如果我的onDraw始于此:
But if my onDraw starts with this:
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
if(mCanvas == null)
{
Log.d("testing","mCanvas is null"
}
LogCat中始终显示消息mCanvas为空当我到达的onDraw。
logCat always shows the message "mCanvas is null" when i reach onDraw.
所以我改变了code,这样如果mCanvas为空,当我读到的onDraw我只是重新创建它:
So i changed the code so that if mCanvas is null when i read onDraw i just create it again:
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中仍然打印帆布依然空
logCat still prints "canvas is still null"
有人能解释这里发生了什么?我非常新的Android和大多数这个code是从我一直在玩的touchpaint例子。
Can someone explain what is happening here? I'm very new with android and most of this code is from the touchpaint example that i've been playing with.
如果我检查resizeCanvas函数内部如果mCanvas为null,它总是说,这是不为空。但是,如果我只是检查调用该函数后,它始终为空。
If i check inside the resizeCanvas function if mCanvas is null it always says it is not null. But if i check just after calling that function it is always null.
推荐答案
我认为这个问题是在你的 resizeCanvas
<$ C $,你可以从它初始化之前返回C> mCanvas 。
I think the problem is in your resizeCanvas
as you can return from it before initializing mCanvas
.
这篇关于成员变量是在函数返回空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!