如何在android 4.2中显示选项菜单

时间:2013-07-16 02:55:17

标签: android menuitem

我正在尝试在我的测试应用程序中创建菜单选项。

当我将清单中的主题设置为默认时,我能够看到菜单(菜单显示在顶部)。如果我将清单中的主题设置为NoTitleBar。我看不到菜单选项?

我想在清单中设置主题“NoTitleBar”时获取菜单。

如何解决?

以下是我在测试应用程序中使用的内容:

with Manifest:

  <uses-sdk
      android:minSdkVersion="8"
    android:targetSdkVersion="17" />

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.NoTitleBar" >
    <activity
        android:name="com.ssn.menuoptions.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

</manifest>

并且

menu.xml文件

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android">
 <item android:id="@+id/menu_preferences"
      android:title="Preferences" /> 
 </menu>

Java文件:

@Override
public boolean onCreateOptionsMenu(Menu menu) 
    {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

是否有可能得到这样的东西:

file:///C:/Users/Koushik/Downloads/SahayaPictures/fHEQ8.png

如何让菜单显示下来?

谢谢!

4 个答案:

答案 0 :(得分:2)

在Activity.setContentView();

下面添加以下代码
 setContentView(R.layout.activity_detail);
    // set option menu if has no hardware menu key
    boolean hasMenu = ViewConfiguration.get(this).hasPermanentMenuKey();
    if(!hasMenu){
        //getWindow().setFlags(0x08000000, 0x08000000);
        try {
            getWindow().addFlags(WindowManager.LayoutParams.class.getField("FLAG_NEEDS_MENU_KEY").getInt(null));
          }
          catch (NoSuchFieldException e) {
            // Ignore since this field won't exist in most versions of Android
          }
          catch (IllegalAccessException e) {
            Log.w("Optionmenus", "Could not access FLAG_NEEDS_MENU_KEY in addLegacyOverflowButton()", e);
          }
    }

答案 1 :(得分:1)

如果您不想在应用中使用操作栏,则可以使用此处理程序设置一个按钮:

myButton.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View arg0) { openOptionsMenu(); }
});

现在myButton的工作方式与菜单键相似。这是将全屏应用程序迁移到4.x的简单方法,但应该寻求更长期的更优雅的解决方案。

答案 2 :(得分:0)

使用notitlebar主题会删除菜单按钮所在的操作栏。你可能不得不制作一个自定义主题来包含你的菜单。 如果您没有采取任何措施,您至少可以使用此属性:android:showAsAction="Never",以便拥有菜单按钮的手机用户可以使用按钮弹出菜单。

答案 3 :(得分:0)

添加Android Manifest android:targetSdkVersion =“10”

<uses-sdk
    android:targetSdkVersion="10" />