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

java-函数返回后成员变量为null?,第1张

概述我有一个扩展View的类.此类具有成员变量mCanvasprivateCanvasmCanvas;调整视图大小时将创建此变量,因此将设置画布的适当大小:@OverrideprotectedvoidonSizeChanged(intw,inth,intoldw,intoldh){intcurW=mBitmap!=null?mBitmap.getWidth():0;

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

private Canvas mCanvas;

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

@OverrIDeprotected 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以此开始:

@OverrIDeprotected 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;}@OverrIDeprotected 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之前从中返回.

总结

以上是内存溢出为你收集整理的java-函数返回后成员变量为null?全部内容,希望文章能够帮你解决java-函数返回后成员变量为null?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1210781.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-04
下一篇 2022-06-04

发表评论

登录后才能评论

评论列表(0条)

保存