android - Android 上的 DRY 选项菜单

标签 android android-menu

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

guide它有以下保持菜单干燥的提示:

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.

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

最佳答案

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

public class YourRootActivity extends Activity {

// Any other stuff that you want for all activities

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

现在对于需要这个菜单的类,让它们扩展我们上面创建的 Activity 。

class Activity1 extends YourRootActivity {
}

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

关于android - Android 上的 DRY 选项菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6314115/

相关文章:

android - 强制设置生效

android - 设置 MenuItem onPressed Action Android Action 条?最好是程序化的

java - 对于我不明白的事情,在这里得到一个空指针异常

java - com.parse.ParseRequest$ParseRequestException : unauthorized

android - 使用带有 Android 客户端的 Tastypie Django 上传文件

android - 如何开始新 Activity 实现RadioGroup.OnCheckedChangeListener

android - 如何通过实现 parcable 通过 Intent 发送类对象。无法编码值错误

android - Android 上下文菜单创建中的 getMenuInflater() 方法未定义问题

android - PopupWindow - 在外部单击时关闭

android - 如何在工具栏中为不同的 fragment 设置不同的菜单?