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

How to display menu options in android?

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

这是我的清单的样子:

 <?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>

如果您使用片段,请确保您已使用 setHasOptionsMenu(true) 启用选项菜单。调用它的好地方可能来自 onCreate

public class MyFragment extends Fragment {

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

或 Activity

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;
    }

}

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

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

或在onCreate()

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

试试这个:

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