我正在学习如何为 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/