Android没有菜单项在布局中显示

时间:2016-11-30 11:54:30

标签: android xml android-layout menu

我在菜单设计中可以看到这样的图片

http://imgur.com/a/rBLbo

但是当我切换到布局设计时

http://imgur.com/a/rw2iB

我再也看不到菜单了。

我已经检查了菜单设置

  1. 制作onCreateOptionsMenu

  2. 设置menu / main.xml

  3. xmlns:tools / tools:context

  4. 但它仍然没有菜单栏。 代码如下:

    MainActivity.java

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
    

    布局/ activity_main.xml中

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin"
    tools:context="com.example.jason.web_control.MainActivity">
    
        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent">
    
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_above="@+id/playPauseButton"
                android:clickable="true"
                android:background="@android:color/holo_blue_dark"
                android:id="@+id/mousePad"
                android:layout_alignParentLeft="true"
                android:layout_alignParentStart="true" />
    
        </RelativeLayout>
    </LinearLayout>
    

    菜单/ menu_main.xml

    <menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    tools:context="com.example.jason.web_control.MainActivity">
    <item
        android:id="@+id/action_settings"
        android:title="@string/action_settings"
        app:showAsAction="always" />
    </menu>
    

2 个答案:

答案 0 :(得分:1)

请在代码中包含此行 setHasOptionsMenu(true);

答案 1 :(得分:0)

    What I did was                                                                                        

    public MoviesFragment() {
        setHasOptionsMenu(true);
    }
and need to override                                                                                          
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        switch (id) {

        }
       return super.onOptionsItemSelected(item);
    }