java - 为多项 Activity 实现一次选项菜单

标签 java android

我正在尝试为我的应用程序实现一个选项菜单,并且在不同的 Activity 中使用相同的菜单。在Android developers site ,它说了以下内容:

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 can manage one set of code for handling menu actions and each descendant class inherits the menu behaviors. If you want to add menu items to one of the descendant activities, override onCreateOptionsMenu() in that activity. Call super.onCreateOptionsMenu(menu) so the original menu items are created, then add new menu items with menu.add(). You can also override the super class's behavior for individual menu items.

我的 Activity 是从 Activity、ListActivity 或 MapActivity 扩展而来的,那么实现他们在这里建议的内容的正确方法是什么?可能吗?因为我不能为所有这些扩展这个新类,所以我只能做类似 public abstract BaseMenu extends Activity 的事情(如 this question 中所述),但这对我不起作用。所以我想知道是否有我可以实现的解决方法。

提前致谢

最佳答案

对于那个通用的基本菜单类,您需要扩展 MapActivity 类。因此,您可以为所有 Activity 扩展该通用基本菜单类。

对于那个ListActivity你也可以实现不带ListActivity的列表,你可以只用Activity或者MapActivity来实现。

您必须在 xml 文件中使用如下 id 声明您的 ListView 。

 <ListView
            android:id="@+id/listView"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"/>

然后你必须在你的 Activity 类中声明它。

ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(your adapter);

像上面一样,您可以在不扩展 ListActivity 的情况下实现它。

关于java - 为多项 Activity 实现一次选项菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9764907/

相关文章:

java - java中的注释帮助

android - Activity 与 Fragment 交互

android - 缺少 Content_main.xml

Android - 一个应用程序中有两个或多个 GCM token

android - 运行cordova build –release android时出错

Java hibernate 查询中 order by 子句的问题

java - 初始化包含 main() 的类时出现 "Could not find the main class, program will exit"?

java - 在 Java 中生成多个形状......?

java - 如何在 JNI 调用中使用全局引用

java - 在 IIS 中运行 Java Web 应用程序