1

I read Hello Android book and I don't understand some parts of the code.

public class PuzzleView extends View {
    private static final String TAG = "Sudoku" ;
    private final Game game;
    public PuzzleView(Context context) {
    super(context);
    this.game = (Game) context;
    setFocusable(true);
    setFocusableInTouchMode(true);
  }
 // ...
}

private float width; // width of one tile
private float height; // height of one tile
private int selX; // X index of selection
private int selY; // Y index of selection
private final Rect selRect = new Rect();
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
    width = w / 9f;
    height = h / 9f;
    getRect(selX, selY, selRect);
    Log.d(TAG, "onSizeChanged: width " + width + ", height "+ height);
    super.onSizeChanged(w, h, oldw, oldh);
 }

super(context); in this code, what does it mean and what does it do?

this.game = (Game) context; why we wrote this? what does it do?

The Android site says that onSizeChanged() function is used for: "This is called during layout when the size of this view has changed" This meant that if to rotate the phone, this function causes the view of program to display true. this is true?

getRect(selX,selY,selRect); what does it mean and what does it do?

Please help me. Cheers.

4

2 回答 2

2

For your first question, Subclasses can call super class constructors with a call to super()

i.e.

super(context);

calls the super class constructor:

public View(Context context)

In your second question, this.game = (Game) context; does 2 things. Firstly, it casts context to class Game and then it assigns it to the PuzzleView's game field (private final Game game;).

getRect is declared at the end of the PuzzleView code. It changes the variable rect passed to it.

   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));

ATaylor has already addressed onSizeChanged. Basically, the code overrides the inherited method, and then 'hooks' in additional functionality, before calling the super method. This is standard practice for overriding virtual methods (i.e. polymorphic behaviour).

于 2012-09-08T05:41:25.447 回答
2

如前所述:

super(context);

会调用父类同名的函数。

假设你有这种多态性:Class Animal

void MakeNoise() {
    System.out.println("Generic Noise");
}

类狗扩展动物

void MakeNoise() {
    super();
    System.out.println("Woof");
}

当您从 Dog 对象调用 MakeNoise 时,您将有两个输出。

通用噪声(由“super”调用)和“Woof”。

this.game => 当然,您需要访问该类中的绘图上下文,为此您需要一个“游戏”类型的上下文(我不熟悉 Android,这就是为什么我不确定,什么类型“游戏”是,但它似乎与上下文兼容。

每当从该类访问“this.game”时,它将访问最初传递的上下文,从而在设备表面上绘制。

是的,只要视图的大小发生变化,就会触发 onSizeChanged。

关于 getRect:实际上没有线索,因为我缺少原型或函数声明。但从它的外观来看,它将采用任意值(因为传递的参数尚未初始化,据我所知),并从中构造一个“矩形”结构(X/Y 到 W/Z)

于 2012-09-08T05:55:06.427 回答