java – 什么原因导致调用View的OnDraw方法以及何时调用

我在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) {
}

如果它是空的,为什么有人会调用超级类的方法呢?

使用参数canvas调用方法在哪里?

参数画布是由android系统自动传递的吗?

什么时候提取方法叫谁?

当它被覆盖时,是否调用了子类的方法而不是超类’?

这是我的自定义视图,例如:

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,这样你就可以决定你的视图的外观

Is the parameter canvas passed automatically by the android system?

When is ondraw method called and by whom?

当它第一次变得可见时,它被活动的某个地方连接到它.你不必担心.当您在View上调用invalidate或将其视为脏(需要重绘)时,也会调用它.在您的示例中,将调用onDraw,但由于您没有在提供的画布上绘制任何内容,因此您不会在Activity上看到任何内容.如果您向该函数添加一些日志,您将在logcat中看到它

When it’s overridden,is the method of subclass called instead of superclass’?

是的,这就是扩展类和重写方法方法

相关文章

Android性能优化——之控件的优化 前面讲了图像的优化,接下...
前言 上一篇已经讲了如何实现textView中粗字体效果,里面主要...
最近项目重构,涉及到了数据库和文件下载,发现GreenDao这个...
WebView加载页面的两种方式 一、加载网络页面 加载网络页面,...
给APP全局设置字体主要分为两个方面来介绍 一、给原生界面设...
前言 最近UI大牛出了一版新的效果图,按照IOS的效果做的,页...