Android - WallpaperService 为什么我的引擎必须是内部类?
我正在制作一个简单的 Android 动态壁纸,我按照 Hello, Android 的第 12 章作为我的指南。
壁纸服务的基本结构如下所示:
public class MyWallpaper extends WallpaperService {
private class MyEngine extends Engine {
//...
}
//...
}
根据MyEngine
一书,必须是MyWallpaper
的内部类。我没有理由对此提出异议,但是这本书没有解释为什么会这样。我不喜欢纯粹出于风格/美学原因而使用内部类。
我想知道 MyEngine
是否实际上必须是私有内部类,如果是的话,为什么?
I'm working on a simple android live wallpaper, I'm following chapter 12 from Hello, Android as my guide.
The bare-bones of a wallpaper service looks like this:
public class MyWallpaper extends WallpaperService {
private class MyEngine extends Engine {
//...
}
//...
}
According to the book MyEngine
must be an inner class of MyWallpaper
. I have no reason to dispute this, but the book offers no explanation as to why this must be so. I prefer not to use inner classes purely for stylistic/aesthetic reasons.
I was wondering if MyEngine
actually has to be a private inner class and, if so, why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该这样做,因为
class Engine
嵌套在抽象类WallpaperService
中。如果您尝试使其不嵌套,您的 IDE/编译器会告诉您如下信息:粗略地翻译,这意味着“你可以这样做,但最终会比只使用嵌套类更难看”。
You're supposed to do it this way because
class Engine
is nested within theabstract class WallpaperService
. If you try to make it not nested, your IDE/compiler will tell you something like this:Which, loosely translated, means "you could do it that way, but it's going to end up uglier than if you just use the nested class."
你可以将你的引擎放在一个单独的类中。我刚刚使用自己的壁纸进行了尝试,它编译并运行良好。在您的 WallpaperService 子类中的 onCreateEngine() 重写中,只需将“this”传递给您的引擎构造函数即可。构造函数应该将其作为壁纸服务接收。在构造函数的第一行中,调用 wallSvcObject.super()。编辑:在考虑 Justin Buser 所说的内容后,我不确定我的建议是否好。您的引擎将失去对WallpaperService成员的访问,因为它都必须通过wallpaperSvcObject。我不知道他指的是不是这个。
You CAN have your Engine in a separate class. I just tried it with my own wallpaper and it compiled and runs fine.In the onCreateEngine() override in your WallpaperService subclass, just pass 'this' to your Engine constructor. The constructor should receive it as a WallpaperService. In the first line of your constructor, make a call to wallpaperSvcObject.super().EDIT: After thinking about what Justin Buser said, I'm not sure if my advice is good. Your Engine would lose access to members of WallpaperService because it'd all have to go through wallpaperSvcObject. I don't know if that's what he was referring to.