콘텐츠로 건너뛰기

자주 방문한 페이지

최근 방문한 페이지

navigation

Setting Up the Search Interface

Beginning in Android 3.0, using the SearchView widget as an item in the app bar is the preferred way to provide search in your app. Like with all items in the app bar, you can define the SearchView to show at all times, only when there is room, or as a collapsible action, which displays the SearchView as an icon initially, then takes up the entire app bar as a search field when the user clicks the icon.

Note: Later in this class, you will learn how to make your app compatible down to Android 2.1 (API level 7) for devices that do not support SearchView.

Add the Search View to the App Bar

To add a SearchView widget to the app bar, create a file named res/menu/options_menu.xml in your project and add the following code to the file. This code defines how to create the search item, such as the icon to use and the title of the item. The collapseActionView attribute allows your SearchView to expand to take up the whole app bar and collapse back down into a normal app bar item when not in use. Because of the limited app bar space on handset devices, using the collapsibleActionView attribute is recommended to provide a better user experience.

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/search"
          android:title="@string/search_title"
          android:icon="@drawable/ic_search"
          android:showAsAction="collapseActionView|ifRoom"
          android:actionViewClass="android.widget.SearchView" />
</menu>

Note: If you already have an existing XML file for your menu items, you can add the <item> element to that file instead.

To display the SearchView in the app bar, inflate the XML menu resource (res/menu/options_menu.xml) in the onCreateOptionsMenu() method of your activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    return true;
}

If you run your app now, the SearchView appears in your app's app bar, but it isn't functional. You now need to define how the SearchView behaves.

Create a Searchable Configuration

A searchable configuration defines how the SearchView behaves and is defined in a res/xml/searchable.xml file. At a minimum, a searchable configuration must contain an android:label attribute that has the same value as the android:label attribute of the <application> or <activity> element in your Android manifest. However, we also recommend adding an android:hint attribute to give the user an idea of what to enter into the search box:

<?xml version="1.0" encoding="utf-8"?>

<searchable xmlns:android="http://schemas.android.com/apk/res/android"
        android:label="@string/app_name"
        android:hint="@string/search_hint" />

In your application's manifest file, declare a <meta-data> element that points to the res/xml/searchable.xml file, so that your application knows where to find it. Declare the element in an <activity> that you want to display the SearchView in:

<activity ... >
    ...
    <meta-data android:name="android.app.searchable"
            android:resource="@xml/searchable" />

</activity>

In the onCreateOptionsMenu() method that you created before, associate the searchable configuration with the SearchView by calling setSearchableInfo(SearchableInfo):

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.options_menu, menu);

    // Associate searchable configuration with the SearchView
    SearchManager searchManager =
           (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    SearchView searchView =
            (SearchView) menu.findItem(R.id.search).getActionView();
    searchView.setSearchableInfo(
            searchManager.getSearchableInfo(getComponentName()));

    return true;
}

The call to getSearchableInfo() obtains a SearchableInfo object that is created from the searchable configuration XML file. When the searchable configuration is correctly associated with your SearchView, the SearchView starts an activity with the ACTION_SEARCH intent when a user submits a query. You now need an activity that can filter for this intent and handle the search query.

Create a Searchable Activity

A SearchView tries to start an activity with the ACTION_SEARCH when a user submits a search query. A searchable activity filters for the ACTION_SEARCH intent and searches for the query in some sort of data set. To create a searchable activity, declare an activity of your choice to filter for the ACTION_SEARCH intent:

<activity android:name=".SearchResultsActivity" ... >
    ...
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    ...
</activity>

In your searchable activity, handle the ACTION_SEARCH intent by checking for it in your onCreate() method.

Note: If your searchable activity launches in single top mode (android:launchMode="singleTop"), also handle the ACTION_SEARCH intent in the onNewIntent() method. In single top mode, only one instance of your activity is created and subsequent calls to start your activity do not create a new activity on the stack. This launch mode is useful so users can perform searches from the same activity without creating a new activity instance every time.

public class SearchResultsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        ...
        handleIntent(getIntent());
    }

    @Override
    protected void onNewIntent(Intent intent) {
        ...
        handleIntent(intent);
    }

    private void handleIntent(Intent intent) {

        if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
            String query = intent.getStringExtra(SearchManager.QUERY);
            //use the query to search your data somehow
        }
    }
    ...
}

If you run your app now, the SearchView can accept the user's query and start your searchable activity with the ACTION_SEARCH intent. It is now up to you to figure out how to store and search your data given a query.

이 사이트는 쿠키를 사용하여 사이트별 언어 및 표시 옵션에 대한 환경설정을 저장합니다.

Google Play에서 성공을 거두는 데 도움이 되는 최신 Android 개발자 뉴스 및 도움말을 받아 보세요.

* 필수 입력란

완료되었습니다.

WeChat에서 Google Developers 팔로우하기

이 사이트를 (으)로 탐색할까요?

페이지를 요청했지만 이 사이트의 언어 환경설정은 입니다.

언어 환경설정을 변경하고 이 사이트를 (으)로 탐색할까요? 언어 환경설정을 나중에 변경하려면 각 페이지 하단의 언어 메뉴를 사용하세요.

이 클래스를 사용하려면 API 수준 이상이 필요합니다.

문서에 대해 선택한 API 수준이 이므로 이 문서가 표시되지 않습니다. 왼쪽 탐색 메뉴의 선택기로 문서 API 수준을 변경할 수 있습니다.

앱에 필요한 API 수준 지정에 관한 자세한 내용은 다양한 플랫폼 버전 지원을 참조하세요.

Take a short survey?
Help us improve the Android developer experience. (April 2018 — Developer Survey)