我在 android 的 Textview 类中看到了这个:
@Override
protected void onDraw(Canvas canvas) {
restartMarqueeIfNeeded();
// Draw the background for this view
super.onDraw(canvas);
在android的View
类中,我看到它是空的:
/**
* Implement this to do your drawing.
*
* @param canvas the canvas on which the background will be drawn
*/
protected void onDraw(Canvas canvas) {
}
如果它是空的,为什么有人会调用父类(super class)的方法?
调用参数canvas的方法在哪里?
参数canvas是android系统自动传过来的吗?
ondraw 方法是什么时候调用的,由谁调用?
重写时,调用的是子类的方法而不是父类的方法吗?
例如,这是我的自定义 View :
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new MyView(this));
}
}
class MyView extends View {
public MyView(Context context) {
super(context);
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
}
}
谁调用了 MyView.OnDraw 方法?
一定有一行代码调用了Myview.Ondraw方法,不是吗?
最佳答案
回答您的问题:
Why would anybody call method of super class if it's empty?
因为如果您不确定实现是什么,最好调用 super。例如,如果你有一个库中类的扩展类,而你没有它的代码,你应该调用 super 方法。然而,在这种情况下,没有必要,但我会推荐它
Where is the method called with parameter canvas?
我不完全确定你的意思,但是当你让你的类覆盖 View
时,你可以覆盖 onDraw
这样你就可以决定你的 View 的外观
Is the parameter canvas passed automatically by the android system?
是
When is ondraw method called and by whom?
当它第一次变得可见时,它被它附加到其生命周期中某处的 Activity 调用。您不必为此担心。当您在 View 上调用 invalidate
或当它被认为是脏的(需要重绘)时,它也会被调用。在您的示例中,将调用 onDraw
但由于您没有在提供的 Canvas 上绘制任何内容,因此您不会在 Activity 上看到任何内容。如果您向该函数添加一些日志,您将在 logcat 中看到它出现
When it's overridden ,is the method of subclass called instead of superclass'?
是的,这就是扩展类和覆盖方法的方式
关于java - 是什么导致调用 View 的 OnDraw 方法以及何时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35579116/