AndroidX 라이브러리의 Toolbar는 사용자가 앱과 상호작용할 수 있는 다양한 방법을 제공합니다. 작업 추가 및 처리에서는 버튼이나 메뉴 항목일 수 있는 작업을 정의하는 방법을 설명합니다. 이 문서에서는 다음과 같은 다목적 구성요소 2개를 추가하는 방법을 설명합니다.
작업 뷰: 앱바 내에 풍부한 기능을 제공하는 작업입니다. 예를 들어 검색 작업 뷰를 사용하면 사용자가 활동이나 프래그먼트를 변경하지 않고도 앱 바에 검색 텍스트를 입력할 수 있습니다.
작업 제공자: 고유한 맞춤 레이아웃이 사용된 작업입니다. 작업은 처음에 버튼이나 메뉴 항목으로 표시되지만, 사용자가 작업을 탭하면 개발자가 정의한 방법대로 작업 제공자가 작업의 동작을 제어합니다. 예를 들어 작업 제공자는 탭에 응답하여 메뉴를 표시할 수 있습니다.
AndroidX는 특수한 작업 뷰 위젯과 작업 제공자 위젯을 여러 개 제공합니다. 예를 들어 SearchView 위젯은 검색어 입력을 위한 작업 뷰를 구현합니다. ShareActionProvider 위젯은 다른 앱과 정보를 공유하기 위한 작업 제공자를 구현합니다. 자체 작업 뷰와 작업 제공자를 정의할 수도 있습니다.
작업 뷰 추가
작업 뷰를 추가하려면 작업 추가 및 처리에 설명된 대로 툴바의 메뉴 리소스에 <item> 요소를 만듭니다. <item> 요소에 다음 속성 중 하나를 추가합니다.
actionViewClass: 작업을 구현하는 위젯의 클래스입니다.
actionLayout: 작업의 구성요소를 설명하는 레이아웃 리소스
showAsAction 속성을 "ifRoom|collapseActionView" 또는 "never|collapseActionView"로 설정합니다. collapseActionView 플래그는 사용자가 위젯과 상호작용하지 않을 때 위젯을 표시하는 방법을 나타냅니다. 위젯이 앱 바에 있는 경우 앱은 위젯을 아이콘으로 표시합니다. 위젯이 더보기 메뉴에 있는 경우 앱은 위젯을 메뉴 항목으로 표시합니다. 사용자가 작업 뷰와 상호작용할 때는 위젯이 확장되어 앱 바를 채웁니다.
사용자가 위젯과 상호작용하지 않는 경우 앱은 위젯을 android:icon에 지정된 아이콘으로 표시합니다. 앱 바에 공간이 없으면 앱은 작업을 더보기 메뉴에 추가합니다.
그림 1. 선행 및 후행 아이콘이 있는 검색창
사용자가 아이콘이나 메뉴 항목을 탭하면 위젯이 확장되어 툴바를 채우고 사용자가 상호작용할 수 있도록 합니다.
그림 2. 검색창에 포커스가 맞춰지면 검색 뷰가 열립니다.
작업을 구성해야 하는 경우 활동의 onCreateOptionsMenu() 콜백에서 구성하면 됩니다. getActionView() 메서드를 호출하여 작업 뷰의 객체 참조를 가져올 수 있습니다. 예를 들어 다음 코드는 이전 코드 예에서 정의한 SearchView 위젯의 객체 참조를 가져옵니다.
Kotlin
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)}
자바
@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);}
작업 뷰 확장에 응답하기
작업의 <item> 요소에 collapseActionView 플래그가 있으면 사용자가 작업 뷰와 상호작용할 때까지 앱은 작업 뷰를 아이콘으로 표시합니다. 사용자가 아이콘을 탭하면 내장된 onOptionsItemSelected() 핸들러가 작업 뷰를 확장합니다. 활동 서브클래스가 onOptionsItemSelected() 메서드를 재정의하는 경우 슈퍼클래스가 작업 뷰를 확장할 수 있도록 재정의 메서드가 super.onOptionsItemSelected()를 호출해야 합니다.
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}
자바
@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;}
작업 제공자 추가
작업 제공자를 선언하려면 작업 추가 및 처리에 설명된 대로 툴바의 메뉴 리소스에 <item> 요소를 만듭니다. actionProviderClass 속성을 추가하고 작업 제공자 클래스의 정규화된 클래스 이름으로 설정합니다.
예를 들어 다음 코드는 AndroidX 라이브러리에 정의된 위젯인 ShareActionProvider를 선언합니다. 이 위젯은 앱이 다른 앱과 데이터를 공유할 수 있도록 합니다.
이 페이지에 나와 있는 콘텐츠와 코드 샘플에는 콘텐츠 라이선스에서 설명하는 라이선스가 적용됩니다. 자바 및 OpenJDK는 Oracle 및 Oracle 계열사의 상표 또는 등록 상표입니다.
최종 업데이트: 2025-07-27(UTC)
[[["이해하기 쉬움","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(UTC)"],[],[],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."]]