104
100

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Toolbar に 13行で SearchView を実装する

Last updated at Posted at 2015-02-08

イメージ

こんなやつです。

searchview.png

ActionBar にも同じ要領で対応できると思います。

コード & XML

onQueryTextSubmit, onQueryTextChange の説明はこちら
http://developer.android.com/reference/android/support/v7/widget/SearchView.OnQueryTextListener.html

Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
toolbar.inflateMenu(R.menu.search);

mSearchView = (SearchView) toolbar.getMenu().findItem(R.id.menu_search).getActionView();
mSearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
    @Override
    public boolean onQueryTextSubmit(String s) {
        return false;
    }
    @Override
    public boolean onQueryTextChange(String s) {
        return false;
    }
});
search.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:id="@+id/menu_search"
        android:icon="@drawable/ic_menu_search"
        android:title="@string/menu_search"
        app:actionViewClass="android.support.v7.widget.SearchView"
        app:showAsAction="always" />
</menu>

補足

メニューをプログラムで書く

Menu menu = toolbar.getMenu();
MenuItem item = menu.add("検索");
item.setIcon(R.drawable.ic_menu_search);
item.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
item.setActionView(mSearchView);

SearchView を開いた状態とする

mSearchView.setIconfied(false);

SearchView からフォーカスを外す(ソフトウェアキーボードを閉じる)

mSearchView.clearFocus();

クエリーヒントを表示する

mSearchView.setQueryHint("ヒント");

SearchView をカスタマイズする

ページ下段の SearchView Widget あたり
http://android-developers.blogspot.jp/2014/10/appcompat-v21-material-design-for-pre.html

104
100
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
104
100

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?