私はViewを拡張するクラスを持っています。関数の復帰後、メンバ変数がnullですか?
@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関数内で私は取得していた:このクラスは、メンバ変数mCanvas
private Canvas mCanvas;
ビューのサイズが変更されたとき、この変数が作成されるので、キャンバスのための適切なサイズが設定されてい私のキャンバスの幅/高さを取得しようとするとnullポインタの例外が発生します。私は、onSizeChangedが実際に呼び出されているときは不安でした。ビューが作成されたときに呼び出されると仮定していました。
しかし、私のonDrawはこれで始まる場合:
@Override
protected void onDraw(Canvas canvas) {
if (mBitmap != null) {
if(mCanvas == null)
{
Log.d("testing","mCanvas is null"
}
logCatはいつも私がonDrawに達したときに、メッセージが "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はまだ「キャンバスはまだnullである」
を印刷し、誰かが何であるかを説明することができますここで起こっている?私はアンドロイドで非常に新しく、このコードのほとんどは私がプレイしてきたタッチペイントの例です。
mCanvasがnullの場合、resizeCanvas関数の内部をチェックすると、常にnullではないと言われます。しかし、その関数を呼び出した直後にチェックすると、常にnullになります。