Android 上的 DRY 选项菜单

发布于 2024-11-14 23:31:49 字数 509 浏览 5 评论 0原文

我正在学习如何为 Android 应用程序创建选项菜单。

指南中,有以下关于保持菜单干燥的提示:

提示:如果您的应用程序包含 多项活动和其中一些 提供相同的选项菜单, 考虑创建一项活动 除了 onCreateOptionsMenu() 和 onOptionsItemSelected() 方法。然后 为每个活动扩展这个类 应该共享相同的选项 菜单。这样,你就必须管理 只需一组代码即可处理菜单 动作和每个后代类 继承菜单行为。

这看起来是有问题的。如果需要共享相同选项的 Activity 继承自不同的类,那么我的 OptionsMenuActivity 应该继承自什么?我读到Java不支持多重继承,那么如何解决这个问题呢?

I'm learning about creating Options Menus for Android apps.

In the guide it has the following tip for staying DRY with menus:

Tip: If your application contains
multiple activities and some of them
provide the same Options Menu,
consider creating an activity that
implements nothing except the
onCreateOptionsMenu() and
onOptionsItemSelected() methods. Then
extend this class for each activity
that should share the same Options
Menu. This way, you have to manage
only one set of code for handling menu
actions and each descendant class
inherits the menu behaviors.

This appears problematic. If the Activitys that need to share the same options inherit from different classes, what should my OptionsMenuActivity inherit from? I read that Java does not support multiple inheritance, so how do you get around this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

峩卟喜欢 2024-11-21 23:31:49

具有选项菜单代码的活动应该扩展 Activity 类。

public class YourRootActivity extends Activity {

// Any other stuff that you want for all activities

 public boolean onCreateOptionsMenu(Menu menu){
 // your main options menu
 }
}

现在,对于需要此菜单的类,让它们扩展我们上面创建的活动。

class Activity1 extends YourRootActivity {
}

如果您想对子类中的选项菜单进行轻微修改,您可以覆盖这些类中的 onCreateOptionsMenu 方法。

Your activity that has the code for options menu should extend the Activity class.

public class YourRootActivity extends Activity {

// Any other stuff that you want for all activities

 public boolean onCreateOptionsMenu(Menu menu){
 // your main options menu
 }
}

Now for the classes that need this menu, make them extend the activity that we created above.

class Activity1 extends YourRootActivity {
}

In case you want slight modifications in your options menu in the subclasses, you can overwrite the onCreateOptionsMenu method in those classes.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文