سؤال

I have a Game class

Where I do this

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Log.d(TAG, "onCreate");
    int diff = getIntent().getIntExtra(KEY_DIFFICULTY, DIFFICULTY_EASY);
    puzzle = getPuzzle(diff);
    calculateUsedTiles();
    puzzleView = new PuzzleView(this);
    Log.d(TAG,"new Puxxle");
    setContentView(puzzleView);
    Log.d(TAG,"setContent");
    puzzleView.requestFocus();
}

I have my PuzzleView Class where I have

public PuzzleView(Context context) {
    super(context);
    Log.d(TAG, "puzzleview");
    this.game = (Game) context;
    setFocusable(true);
    setFocusableInTouchMode(true);
}

@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    // TODO Auto-generated method stub
    super.onSizeChanged(w, h, oldw, oldh);
    Log.d(TAG, "w and h" + w + " " + h);
    width = w / 9f;
    height = h / 9f;
    Log.d(TAG, "selY and x" + selX + " " + selY);
    getRect(selX, selY, selRect);
    Log.d(TAG, "selY and x" + selX + " " + selY);
    Log.d(TAG, "onSizeChanged: width " + width + ", height " + height);
    super.onSizeChanged(w, h, oldw, oldh);
}

private void getRect(int x, int y, Rect rect) {
    rect.set((int) (x * width), (int) (y * height),
            (int) (x * width + width), (int) (y * height + height));
}

@Override
protected void onDraw(Canvas canvas) {
    Log.d(TAG,"drawing");
    Paint background = new Paint();
    background.setColor(getResources().getColor(R.color.puzzle_background));
    canvas.drawRect(0, 0, getWidth(), getHeight(), background);
}

Now my understanding was that when, in the Game class, we do setContentView that is when all the onsizeChanged and onDraw will be called, but it is happening after the setContent has been called.

Here's the sequence of my logs

  D/Game    ( 4175): onCreate 
  D/PuzzleView( 4175): puzzleview
  D/Game    ( 4175): new Puxxle
  D/Game    ( 4175): setContent
  D/PuzzleView( 4175): w and h320 430
  D/PuzzleView( 4175): selY and x0 0
  D/PuzzleView( 4175): selY and x0 0
  D/PuzzleView( 4175): onSizeChanged: width 35.555557, height 47.77778
  D/PuzzleView( 4175): drawing
هل كانت مفيدة؟

المحلول

When an Activity receives focus, it will be requested to draw its layout. The Android framework will handle the procedure for drawing, but the Activity must provide the root node of its layout hierarchy.

setContentView() just sets the root node, but the drawing of view occurs at some other point after onCreate().

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top