アプリバーでは、ユーザー アクション用のボタンを追加できます。この機能を使用すると、現在のコンテキストで最も重要なアクションをアプリの一番上に配置できます。たとえば、写真閲覧アプリでは、ユーザーが自分の写真ロールを見ているとき、共有ボタンとアルバム作成ボタンを一番上に表示できます。ユーザーが個々の写真を見ると、アプリに切り抜きボタンとフィルタボタンが表示されます。
アプリバーのスペースには限りがあります。アプリバーに収まらないほど多くのアクションをアプリで宣言している場合、アプリバーは表示できない分のアクションをオーバーフロー メニューに格納します。アプリは、アクションをアプリバーに表示するのではなく、常にオーバーフロー メニューに表示するように指定することもできます。
![アクション バー アイコンが表示された Now in Android アプリを示す画像](https://developer.android.google.cn/static/images/ui/notifications/actions_actionbar.png?authuser=0&hl=ja)
アクション ボタンを追加する
アクション オーバーフローで使用可能なすべてのアクション ボタンとその他のアイテムは、XML メニュー リソースで定義されています。アクションバーにアクションを追加するには、プロジェクトの res/menu/
ディレクトリに新しい XML ファイルを作成します。
次のサンプルのメニュー XML ファイルに示すように、アクションバーに含める各アイテムに <item>
要素を追加します。
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <!-- "Mark Favorite", must appear as action button if possible. --> <item android:id="@+id/action_favorite" android:icon="@drawable/ic_favorite_black_48dp" android:title="@string/action_favorite" app:showAsAction="ifRoom"/> <!-- Settings, must always be in the overflow. --> <item android:id="@+id/action_settings" android:title="@string/action_settings" app:showAsAction="never"/> </menu>
app:showAsAction
属性は、アクションをアプリバーのボタンとして表示するかどうかを指定します。app:showAsAction="ifRoom"
を(サンプルコードの favorite アクションのように)設定すると、アクションのためのスペースがアプリバーにある場合、アクションはボタンとして表示されます。十分なスペースがない場合、超過したアクションがオーバーフロー メニューに送信されます。app:showAsAction="never"
を(サンプルコードの settings アクションのように)設定すると、アクションは常にオーバーフロー メニューにリストされ、アプリバーには表示されません。
アクションがアプリバーに表示されている場合、システムはアクションのアイコンをアクション ボタンとして使用します。マテリアル アイコンには、便利なアイコンが多数用意されています。
アクションに応答する
ユーザーがアプリバーのアイテムのいずれかを選択すると、システムはアクティビティの onOptionsItemSelected()
コールバック メソッドを呼び出し、MenuItem
オブジェクトを渡して、タップされたアイテムを示します。onOptionsItemSelected()
の実装で、MenuItem.getItemId()
メソッドを呼び出して、タップされたアイテムを判別します。返された ID は、対応する <item>
要素の android:id
属性で宣言した値と一致します。
たとえば、次のコード スニペットは、ユーザーが選択したアクションを確認します。メソッドがユーザーのアクションを認識しない場合は、スーパークラス メソッドを呼び出します。
Kotlin
override fun onOptionsItemSelected(item: MenuItem) = when (item.itemId) { R.id.action_settings -> { // User chooses the "Settings" item. Show the app settings UI. true } R.id.action_favorite -> { // User chooses the "Favorite" action. Mark the current item as a // favorite. true } else -> { // The user's action isn't recognized. // Invoke the superclass to handle it. super.onOptionsItemSelected(item) } }
Java
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.action_settings: // User chooses the "Settings" item. Show the app settings UI. return true; case R.id.action_favorite: // User chooses the "Favorite" action. Mark the current item as a // favorite. return true; default: // The user's action isn't recognized. // Invoke the superclass to handle it. return super.onOptionsItemSelected(item); } }