我应该将 super 调用放在 Android 事件处理程序中的哪里?
我在阅读“Hello, Android”时注意到一个问题。
当他在 Activity 中实现 onCreate() 时,看起来像:
{ super.onCreate(..); ... ... }
但 onSizeChanged() 看起来像:
{ ... ... super.onSizeChange(); }
并且他没有在 onDraw() 中调用 super。
我应该把 super call 语句放在哪里?我在android的文档中哪里可以找到答案?
I notice a problem when reading "Hello, Android."
When he implements the onCreate() in an Activity, it looks like:
{ super.onCreate(..); ... ... }
But onSizeChanged() looks like:
{ ... ... super.onSizeChange(); }
And he doesn't call super in onDraw().
Where should I put the super call statement? And where can I find answer in android's document?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在子类中的任何重写方法中,super.methodname() 的位置通常是该方法中的第一个内容(如
onCreate()
中)。但是,有时您需要在调用 super 之前执行其他步骤,因此您可以按照onSizeChanged()
方法执行此操作。超级调用是由这个标准决定的,而不是由任何其他规则决定的。In any overridden method in a sub class, the location of super.methodname() is usually the first thing in that method, (like in
onCreate()
). However, sometimes you need to do additional steps before calling super, so you do this as inonSizeChanged()
method. The super call is determined by this criteria, not by any other rule.在很多情况下,当您考虑被覆盖的功能在总体方案中发生的位置时,这个问题的有用答案就会出现。
如果您要调用充当初始化程序的内容,则
super
调用应该(通常)出现在开头,因为您希望在尝试初始化子类之前初始化基类。如果您正在调用一些充当清理例程的东西,那么
super
调用应该(通常)出现在最后,因为您希望在超类 clean 之前清理所有部分自己起来。对于在任意时间打来的呼叫,这将取决于您被覆盖的呼叫的性质。如果您想在框架执行计算之前执行某些操作,以便影响其结果,则需要在最后调用 super 。如果您想将计算基于超类的计算,则您的
super
调用应该放在开头。简而言之,这没有固定的规则:这取决于您要重写的特定方法的功能。
In a lot of cases, a useful answer to this question comes when you think about where your overridden functionality occurs in the grand scheme of things.
If you're calling something that behaves as an initializer, then the
super
call should (usuall) come at the beginning, because you want the base class to be initialized before you try to initialize your sub class.If you're calling something that behaves as a clean-up routine, then the
super
call should (usually) come at the end, because you want to clean up all of your pieces before the super classes clean themselves up.For calls that come at arbitrary times, it will depend on the nature of your overridden call. If you want to do something before the framework does its computations, so that you can influence their outcome, you will want the
super
call at the end. If you want to base your calculations on the computations of the super class, yoursuper
call should become at the beginning.In short, there's no fixed rule for this: it depends on the functionality of the particular method you're overriding.