Android アクションバーに検索Box配置

Android のアクションバーに検索フィールドを配置する場合

良く使いそうなので、サンプルを書いておく。

res/menu で用意する search_menu.xml
アクションバーで表示する画像として action_search.png を用意して以下のように指定する。
android.widget.SearchView を指定する。

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

res/xml に、searchable.xml を定義して、Manifest で Activity から指定しないとならない。

<?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/action_search_hint">
</searchable>

@string/app_name = アプリケーション名
@string/action_search_hint = 検索のヒント文字列

Manifest の アクティビティの記述、、、Intent filter を定義、

<activity android:name=".SearchActivity" android:launchMode="singleTop">
   <intent-filter>
       <action android:name="android.intent.action.SEARCH"/>
   </intent-filter>
   <meta-data android:resource="@xml/searchable" android:name="android.app.searchable"/>
</activity>

アクティビティ class ののメニューの記述は、、

@Override
public boolean onCreateOptionsMenu(Menu menu){
   getMenuInflater().inflate(R.menu.search_menu, menu);
   SearchManager searchManager = (SearchManager)getSystemService(Context.SEARCH_SERVICE);
   SearchableInfo searchableInfo = searchManager.getSearchableInfo(getComponentName());
   MenuItem menuItem = menu.findItem(R.id.action_search);

   SearchView searchView = (SearchView)menuItem.getActionView();
   searchView.setSearchableInfo(searchableInfo);
   searchView.setIconifiedByDefault(false);

   searchView.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
   return true;
}
@Override
protected void onNewIntent(Intent intent) {
   setIntent(intent);
   if (Intent.ACTION_SEARCH.equals(intent.getAction())==true){
      String query = intent.getStringExtra(SearchManager.QUERY);
      // query = 検索文字列
   }
}


起動すると、、、

f:id:posturan:20160313192537p:plain



虫眼鏡アイコンをタップして検索入力状態は、、、


f:id:posturan:20160313192530p:plain