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

时间:2015-03-11 06:29:13

标签: android menu android-actionbar

我在手机上显示菜单选项时遇到问题。我认为所有代码都正确,但它没有显示。任何帮助将不胜感激。

以下是我的清单的样子:

 <?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.example.drumloopsequencer"
 android:versionCode="1"
 android:versionName="1.0" >

 <uses-sdk
    android:minSdkVersion="11"
    android:targetSdkVersion="21" />

 <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:screenOrientation="landscape"
        android:name=".Main"
        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>

这是onCreateOptionsMenu函数:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mymenu, menu);
return true;
}

,这是菜单xml:

  <?xml version="1.0" encoding="utf-8"?>
  <menu xmlns:android="http://schemas.android.com/apk/res/android" >

  <item 
    android:id="@+id/file"
    android:title="@string/fileTab"
    android:orderInCategory="1"
    android:showAsAction="ifRoom"
    />

  <item 
    android:id="@+id/packs"
    android:title="@string/packsTab"
    android:orderInCategory="2"
    android:showAsAction="ifRoom"
     /> 

  <item 
    android:id="@+id/drumRack"
    android:title="@string/drumRackTab"
    android:orderInCategory="3"
    android:showAsAction="ifRoom"
    />

  </menu>

3 个答案:

答案 0 :(得分:1)

如果您使用的是片段,请确保已使用setHasOptionsMenu(true)启用了选项菜单。拨打此电话的好地方可能来自onCreate

public class MyFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }
}

或活动

public class MyActivity extends Activity {

    @Override
    public boolean onCreateOptionsMenu(Menu menu){
        super.onCreateOptionsMenu(menu);

        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.mymenu, menu);
        return true;
    }

}

答案 1 :(得分:0)

如果您正在使用片段,那么您必须这样做:

//inside constructor
 public MyClassFrag(){
      setHasOptionsMenu(true);
}

onCreate()

 @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

答案 2 :(得分:0)

试试这个:

@Override
public void onAttachedToWindow() {
super.onAttachedToWindow()
openOptionsMenu(); 
};