overridefunonCreateOptionsMenu(menu:Menu?):Boolean{menuInflater.inflate(R.menu.main_activity_actions,menu)valsearchItem=menu?.findItem(R.id.action_search)valsearchView=searchItem?.actionViewasSearchView// Configure the search info and add any event listeners.returnsuper.onCreateOptionsMenu(menu)}
Java
@OverridepublicbooleanonCreateOptionsMenu(Menumenu){getMenuInflater().inflate(R.menu.main_activity_actions,menu);MenuItemsearchItem=menu.findItem(R.id.action_search);SearchViewsearchView=(SearchView)searchItem.getActionView();// Configure the search info and add any event listeners.returnsuper.onCreateOptionsMenu(menu);}
overridefunonCreateOptionsMenu(menu:Menu?):Boolean{menuInflater.inflate(R.menu.options,menu)// Define the listener.valexpandListener=object:MenuItem.OnActionExpandListener{overridefunonMenuItemActionCollapse(item:MenuItem):Boolean{// Do something when the action item collapses.returntrue// Return true to collapse the action view.}overridefunonMenuItemActionExpand(item:MenuItem):Boolean{// Do something when it expands.returntrue// Return true to expand the action view.}}// Get the MenuItem for the action item.valactionMenuItem=menu?.findItem(R.id.myActionItem)// Assign the listener to that action item.actionMenuItem?.setOnActionExpandListener(expandListener)// For anything else you have to do when creating the options menu,// do the following:returntrue}
Java
@OverridepublicbooleanonCreateOptionsMenu(Menumenu){getMenuInflater().inflate(R.menu.options,menu);// Define the listener.OnActionExpandListenerexpandListener=newOnActionExpandListener(){@OverridepublicbooleanonMenuItemActionCollapse(MenuItemitem){// Do something when the action item collapses.returntrue;// Return true to collapse action view.}@OverridepublicbooleanonMenuItemActionExpand(MenuItemitem){// Do something when it expands.returntrue;// Return true to expand the action view.}};// Get the MenuItem for the action item.MenuItemactionMenuItem=menu.findItem(R.id.myActionItem);// Assign the listener to that action item.MenuItemCompat.setOnActionExpandListener(actionMenuItem,expandListener);// For anything else you have to do when creating the options menu,// do the following:returntrue;}
[[["容易理解","easyToUnderstand","thumb-up"],["確實解決了我的問題","solvedMyProblem","thumb-up"],["其他","otherUp","thumb-up"]],[["缺少我需要的資訊","missingTheInformationINeed","thumb-down"],["過於複雜/步驟過多","tooComplicatedTooManySteps","thumb-down"],["過時","outOfDate","thumb-down"],["翻譯問題","translationIssue","thumb-down"],["示例/程式碼問題","samplesCodeIssue","thumb-down"],["其他","otherDown","thumb-down"]],["上次更新時間:2025-07-27 (世界標準時間)。"],[],[],null,["# Use action views and action providers\n\nTry the Compose way \nJetpack Compose is the recommended UI toolkit for Android. Learn how to add components in Compose. \n[App bar →](/develop/ui/compose/components/app-bars) \n| **Note:** For a better approach and user experience, consider gradually migrating your projects to [Jetpack Compose](/jetpack/compose/migrate/strategy).\n\nThe [AndroidX](/jetpack/androidx) library's\n[Toolbar](/reference/androidx/appcompat/widget/Toolbar) provides\ndifferent ways for users to interact with your app.\n[Add and handle actions](/develop/ui/views/components/appbar/actions) describes how to\ndefine an *action*, which can be a button or a menu item. This document describes how to add\ntwo versatile components:\n\n- An *action view* is an action that provides rich functionality within the app bar. For example, a search action view lets the user type their search text in the app bar without having to change activities or fragments.\n- An *action provider* is an action with its own customized layout. The action initially appears as a button or menu item; when the user taps the action, the action provider controls the action's behavior any way you define. For example, the action provider might respond to a tap by displaying a menu.\n\nAndroidX provides several specialized action view and action provider widgets. For example, the\n[SearchView](/reference/androidx/appcompat/widget/SearchView) widget\nimplements an action view for entering search queries. The\n[ShareActionProvider](/reference/androidx/appcompat/widget/ShareActionProvider)\nwidget implements an action provider for sharing information with other apps. You can also define\nyour own action views and action providers.\n\nAdd an action view\n------------------\n\nTo add an action view, create an\n[`\u003citem\u003e`](/guide/topics/resources/menu-resource#item-element)\nelement in the toolbar's menu resource, as described in\n[Add and handle actions](/develop/ui/views/components/appbar/actions). Add one of the following attributes to the\n`\u003citem\u003e` element:\n\n- `actionViewClass`: the class of a widget that implements the action\n- `actionLayout`: a layout resource describing the action's components\n\nSet the `showAsAction` attribute to `\"ifRoom|collapseActionView\"` or\n`\"never|collapseActionView\"`. The `collapseActionView` flag indicates how to\ndisplay the widget when the user isn't interacting with it. If the widget is on the app bar, the app\ndisplays the widget as an icon. If the widget is in the overflow menu, the app displays the widget\nas a menu item. When the user interacts with the action view, it expands to fill the app bar.\n\nFor example, the following code adds a `SearchView` widget to the app bar: \n\n```xml\n\u003citem android:id=\"@+id/action_search\"\n android:title=\"@string/action_search\"\n android:icon=\"@drawable/ic_search\"\n app:showAsAction=\"ifRoom|collapseActionView\"\n app:actionViewClass=\"androidx.appcompat.widget.SearchView\" /\u003e\n```\n\nIf the user isn't interacting with the widget, the app displays the widget as the icon specified\nby `android:icon`. If there isn't room in the app bar, the app adds the action to the\noverflow menu.\n**Figure 1.** Search bar with leading and trailing icons.\n\nWhen the user taps the icon or menu item, the widget expands to fill the toolbar, letting the\nuser interact with it.\n**Figure 2.** Search view opens once the search bar is focused.\n\nIf you need to configure the action, do so in your activity's\n[onCreateOptionsMenu()](/reference/android/app/Activity#onCreateOptionsMenu(android.view.Menu))\ncallback. You can get the action view's object reference by calling the\n[getActionView()](/reference/android/view/MenuItem#getActionView())\nmethod. For example, the following code gets the object reference for the `SearchView`\nwidget defined in the previous code example: \n\n### Kotlin\n\n```kotlin\noverride fun onCreateOptionsMenu(menu: Menu?): Boolean {\n menuInflater.inflate(R.menu.main_activity_actions, menu)\n\n val searchItem = menu?.findItem(R.id.action_search)\n val searchView = searchItem?.actionView as SearchView\n\n // Configure the search info and add any event listeners.\n\n return super.onCreateOptionsMenu(menu)\n}\n```\n\n### Java\n\n```java\n@Override\npublic boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.main_activity_actions, menu);\n\n MenuItem searchItem = menu.findItem(R.id.action_search);\n SearchView searchView =\n (SearchView) searchItem.getActionView();\n\n // Configure the search info and add any event listeners.\n\n return super.onCreateOptionsMenu(menu);\n}\n```\n| **Note:** To improve the look and feel for your `SearchView`, see the [Search component](https://m3.material.io/components/search/overview) in Material Design 3.\n\n### Respond to action view expansion\n\nIf the action's `\u003citem\u003e` element has a `collapseActionView` flag, the\napp displays the action view as an icon until the user interacts with the action view. When the user\ntaps the icon, the built-in handler for\n[onOptionsItemSelected()](/reference/android/app/Activity#onOptionsItemSelected(android.view.MenuItem))\nexpands the action view. If your activity subclass overrides the\n`onOptionsItemSelected()` method, your override method must call\n`super.onOptionsItemSelected()` so the superclass can expand the action view.\n\nIf you want to do something when the action is expanded or collapsed, you can define a class that\nimplements\n[MenuItem.OnActionExpandListener](/reference/android/view/MenuItem.OnActionExpandListener),\nand pass a member of that class to\n[setOnActionExpandListener()](/reference/android/view/MenuItem#setOnActionExpandListener(android.view.MenuItem.OnActionExpandListener)).\nFor example, you might want to update the activity based on whether an action view is expanded or\ncollapsed. The following code snippet shows how to define and pass a listener: \n\n### Kotlin\n\n```kotlin\noverride fun onCreateOptionsMenu(menu: Menu?): Boolean {\n menuInflater.inflate(R.menu.options, menu)\n\n // Define the listener.\n val expandListener = object : MenuItem.OnActionExpandListener {\n override fun onMenuItemActionCollapse(item: MenuItem): Boolean {\n // Do something when the action item collapses.\n return true // Return true to collapse the action view.\n }\n\n override fun onMenuItemActionExpand(item: MenuItem): Boolean {\n // Do something when it expands.\n return true // Return true to expand the action view.\n }\n }\n\n // Get the MenuItem for the action item.\n val actionMenuItem = menu?.findItem(R.id.myActionItem)\n\n // Assign the listener to that action item.\n actionMenuItem?.setOnActionExpandListener(expandListener)\n\n // For anything else you have to do when creating the options menu,\n // do the following:\n\n return true\n}\n```\n\n### Java\n\n```java\n@Override\npublic boolean onCreateOptionsMenu(Menu menu) {\n getMenuInflater().inflate(R.menu.options, menu);\n\n // Define the listener.\n OnActionExpandListener expandListener = new OnActionExpandListener() {\n @Override\n public boolean onMenuItemActionCollapse(MenuItem item) {\n // Do something when the action item collapses.\n return true; // Return true to collapse action view.\n }\n\n @Override\n public boolean onMenuItemActionExpand(MenuItem item) {\n // Do something when it expands.\n return true; // Return true to expand the action view.\n }\n };\n\n // Get the MenuItem for the action item.\n MenuItem actionMenuItem = menu.findItem(R.id.myActionItem);\n\n // Assign the listener to that action item.\n MenuItemCompat.setOnActionExpandListener(actionMenuItem, expandListener);\n\n // For anything else you have to do when creating the options menu,\n // do the following:\n\n return true;\n}\n```\n\nAdd an action provider\n----------------------\n\nTo declare an action provider, create an `\u003citem\u003e` element in the toolbar's menu\nresource, as described in [Add and handle actions](/develop/ui/views/components/appbar/actions). Add an\n`actionProviderClass` attribute, and set it to the fully qualified class name for the\naction provider class.\n\nFor example, the following code declares a `ShareActionProvider`, which is a widget\ndefined in the AndroidX library that lets your app share data with other apps: \n\n```xml\n\u003citem android:id=\"@+id/action_share\"\n android:title=\"@string/share\"\n app:showAsAction=\"ifRoom\"\n app:actionProviderClass=\"androidx.appcompat.widget.ShareActionProvider\"/\u003e\n```\n\nIn this case, it's unnecessary to declare an icon for the widget, since\n`ShareActionProvider` provides its own graphics. If you are using a custom action,\ndeclare an icon.\n\nAdditional resources\n--------------------\n\n- See [ShareActionProvider](/reference/androidx/appcompat/widget/ShareActionProvider) for an example of adding a share action to your top app bar.\n- See [ActionProvider](/reference/androidx/core/view/ActionProvider) for more information about creating a custom action provider."]]