java - 我不明白这段代码

标签 java android superclass

我读了 Hello Android 一书,但我不理解代码的某些部分。

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 (上下文);在此代码中,它是什么意思以及它的作用是什么?

this.game =(游戏)上下文;为什么我们写这个?它有什么作用?

Android 网站说 onSizeChanged() 函数用于: “当此 View 的大小发生变化时,将在布局期间调用” 这意味着如果旋转手机,此功能会使程序 View 显示为真。这是真的吗?

getRect(selX,selY,selRect);这是什么意思,有什么作用?

请帮帮我。 干杯。

最佳答案

如前所述:

super(context);

会调用父类的同名函数。

假设你有这个多态性: 类动物

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

Dog 类扩展了 Animal

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

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

通用噪声(称为“super”)和“Woof”。

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

无论何时从该类访问“this.game”,它都会访问最初传递的上下文,从而在设备表面上绘制。

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

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

关于java - 我不明白这段代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12328328/

相关文章:

android - 我需要在首选项中有一个自定义对话框

java - 如何使用 Android 铃声管理器播放 Assets 文件夹中的铃声?

java - OOP扩展继承问题

java - super.onStart(); 出现奇怪的错误

java - 如何在 Apache httpclient 中使用指数退避策略?

android - 如何从 Activity 与 HostApduService 通信

java - Object.getClass().getSuperclass() 不返回 null?

matlab - 在 MATLAB 中重写子类中的父类(super class)属性设置方法

java - Keytool EC KeyPairGenerator 不可用

java - 如何使用 weblogic 中定义的 Tibco JMS 模块并使用 Spring 向其发布消息