前言

简单记录一下标题栏中Menu的使用。

流水文,之前没记录,这次有空重新简单记录一下。

正文

在Android Studio中新创建一个Module。在res目录创建menu,然后创建一个menu.xml

/res/menu/menu.xml

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/app_menu_1"
        android:title="@string/app_menu_1"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="always" />
    <item
        android:id="@+id/app_menu_2"
        android:title="@string/app_menu_2"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="ifRoom" />
    <item
        android:id="@+id/app_menu_3"
        android:title="@string/app_menu_3"
        android:icon="@mipmap/ic_launcher"
        app:showAsAction="never" />
</menu>

这里app:showAsAction需要介绍一下,有三个参数:

  1. ifRoom 在屏幕空间足够时显示在Toolbar中,否则显示在菜单。

  2. never 永远不显示在Toolbar中,而是一直显示在菜单中。

  3. always 永远显示在Toolbar中,如果屏幕空间不够则不显示。

Toolbar中的action按钮只会显示图标,菜单中的action按钮只会显示文字。如果menu显示在Toolbar中,如果有图标,就只显示图标。

MainActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@SuppressLint("NonConstantResourceId")
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item) {
    switch (item.getItemId()) {
        case R.id.app_menu_1:
            Toast.makeText(this, getText(R.string.app_menu_1), Toast.LENGTH_SHORT).show();
            return true;
        case R.id.app_menu_2:
            Toast.makeText(this, getText(R.string.app_menu_2), Toast.LENGTH_SHORT).show();
            return true;
        case R.id.app_menu_3:
            Toast.makeText(this, getText(R.string.app_menu_3), Toast.LENGTH_SHORT).show();
            return true;
    }
    return super.onOptionsItemSelected(item);
}

经过上面两部,菜单(menu)就差不多显示了。

参考文章

相关文章

暂无评论

none
暂无评论...