如何在Android中将菜单设置为工具栏 [英] How to set menu to Toolbar in Android

查看:94
本文介绍了如何在Android中将菜单设置为工具栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要使用ToolBar而不是ActionBar,但不要在工具栏中显示菜单!我想要设置菜单,例如ActionBar中的刷新设置按钮.

I want use ToolBar instead of ActionBar, but don't show me menu in toolbar!!! i want set menu such as Refresh or Setting buttons in ActionBar.

Toolbar.xml代码:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?attr/colorPrimary"
    android:minHeight="?attr/actionBarSize"
    app:navigationContentDescription="@string/abc_action_bar_up_description"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
    app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
    app:title="Main Page"
    android:gravity="center"/>

MainPage.java代码:

public class MainPage extends AppCompatActivity {
    private Toolbar toolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);

        toolbar = (Toolbar) findViewById(R.id.main_toolbar);
        setSupportActionBar(toolbar);
        if (getSupportActionBar() != null) {
            getSupportActionBar().setTitle("Main Page");
        }
        toolbar.setSubtitle("Test Subtitle");
        toolbar.inflateMenu(R.menu.main_manu);
    }
}

main_menu.xml代码:

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

    <item
        android:id="@+id/menu_main_setting"
        android:icon="@drawable/ic_settings"
        android:orderInCategory="100"
        app:showAsAction="always"
        android:actionLayout="@layout/toolbar"
        android:title="Setting" />

    <item
        android:id="@+id/menu_main_setting2"
        android:icon="@drawable/ic_settings"
        android:orderInCategory="200"
        app:showAsAction="always"
        android:actionLayout="@layout/toolbar"
        android:title="Setting" />

</menu>

如何解决此问题并在Toolbar中显示菜单?谢谢所有亲爱的< 3

How to fix this problem and show menu in Toolbar ? thanks all dears <3

推荐答案

只需在MainPage.java

just override onCreateOptionsMenu like this in your MainPage.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, menu);
    return true;
}

这篇关于如何在Android中将菜单设置为工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆