Activityにmenuを追加する方法です。
menuはtoolbar上にある下のようなuiのことです。

画像では、ActivityにBottomNavigationをUIとして保持しており、
表示にはFragmentを使用しています。

Menuを表示するために必要なToolbarはActivityのレイアウトxmlに保持しているので、
Activityの実装から見ていきます。

ActivityにMenuを追加する

まずは、activityのxmlから

注目すべきなのは、
android.support.v7.widget.toolbar
です。

MenuはToolbarのUIの一つなので、Toolbarを定義する必要があります。
また、DesginSupportLibraryでtoolbarが用意されており、今回はそちらを使っているため、
gradleファイルに記載しなければいけません。

対象バージョンは、version 24.2.0です。

続いて、Acitvityのソースを見ていきます。

Toolbarをインスタンス化し、supportActionbarにセットしているだけです。今回は、Fragment常にMenuを出現させるので、Menuの表示等の処理はFragmentで行います。

FragmentにMenuを表示する

まず、メニューのxmlを定義します。
Overrideメソッドの
onCreateOptionMenu
ないで、使用するレイアウトファイルを指定してください。

続いて、メニューがタップされた際に呼ばれる
onOptionsItemSelected
です。

MenuItemのidによって、タップ処理の場合分けをしているのみになります。

最後にmenuのレイアウトとなるxmlを見ます。

OptionMenuのレイアウトxmlファイル

itemの内に記載した属性を見ていきます。

android:showAsActionKeyword. When and how this item should appear as an action item in the app bar. A menu item can appear as an action item only when the activity includes an app bar. Valid values:

Value Description
ifRoom Only place this item in the app bar if there is room for it. If there is not room for all the items marked "ifRoom", the items with the lowest orderInCategory values are displayed as actions, and the remaining items are displayed in the overflow menu.
withText Also include the title text (defined by android:title) with the action item. You can include this value along with one of the others as a flag set, by separating them with a pipe |.
never Never place this item in the app bar. Instead, list the item in the app bar’s overflow menu.
always Always place this item in the app bar. Avoid using this unless it’s critical that the item always appear in the action bar. Setting multiple items to always appear as action items can result in them overlapping with other UI in the app bar.
collapseActionView The action view associated with this action item (as declared by android:actionLayout orandroid:actionViewClass) is collapsible.
Introduced in API Level 14.

See the Adding the App Bar training class for more information.

Introduced in API Level 11.

orderInCategory
メニューの並び順。
昇順に並びます。

 

Pocket