Last Updated: July 25, 2019
·
5.832K
· STK

Androidに検索機能とリスト表示を追加する方法

検索結果ページのアクションバー

  • Android 3.0を用意する。AndroidはSearchViewウェジットをアクションバーに追加する機能をサポートしています。この検索結果ページはリスト表示機能にも使えます。

SearchView に関する詳細はこちら
http://developer.android.com/training/search/setup.html

  • ここから先は検索可能なリスト表示の実装方法です

メニュー検索を追加する

  • メニューに必要なリソースを検索メニューアイテムとと一緒に用意する。(検索メニューアイテムを選択すると、検索ウェジットがアクションバーに表示されます)
  • 下記はサンプルのメニューリソースです。
<?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+id/search"
        android:title="Search"
        android:icon="@drawable/search"
        android:showAsAction="collapseActionView|ifRoom"
        android:actionViewClass="android.widget.SearchView" />
</menu>
  • 上記のcollapseActionView属性のメニューアイテムは、SearchViewがアクションバーに広がり、使用していないときは通常のアクションバーアイテムの状態に戻ります。

検索可能な設定を作る

  • Searchable ConfigurationはSearchViewがどのように動くか定義します。 xml(res/xml/searchable.xml)の形で定義付けする必要があります。下記がサンプルのsearchable configurationファイルです。
<?xml version="1.0" encoding="utf-8"?>
<searchable
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:label="@string/app_name"
    android:hint="Search friend">
</searchable>
  • そして、アクションに関連する要素を<meta-data> と一緒に追加します。
<activity
    android:name=".ui.FriendListActivity"
    android:screenOrientation="portrait"
    android:configChanges="orientation"
    android:theme="@style/Theme.Yello"
    android:windowSoftInputMode="stateHidden"
    android:launchMode="singleTask"
    android:parentActivityName=".ui.SensorDetailsActivity">
    <meta-data
        android:name="android.app.searchable"
        android:resource="@xml/searchable">
    </meta-data>
</activity>
  • シナリオ例として、SearchViewにFriendListActivityを追加します。

activityにSearchableConfigurationとメニューを追加する

  • activityクラスにsearchable configurationとSearchView を関連付けします。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.search_menu, menu);

    SearchManager searchManager = (SearchManager)
                            getSystemService(Context.SEARCH_SERVICE);
    searchMenuItem = menu.findItem(R.id.search);
    searchView = (SearchView) searchMenuItem.getActionView();

    searchView.setSearchableInfo(searchManager.
                            getSearchableInfo(getComponentName()));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(this);

    return true;
}
  • これでActivityにSearchViewが追加されました。しかし検索機能は完全に機能していません

検索機能を追加する

  • ActivityにSearchView.OnQueryTextListenerを実装します。2つの新しいメソッドにオーバーライドする必要があります。
public boolean onQueryTextSubmit(String query)
public boolean onQueryTextChange(String newText)
  • このインターフェースはSearchViewのText Change Eventに影響されます
@Override
public boolean onQueryTextSubmit(String query) {
    return false;
}

@Override
public boolean onQueryTextChange(String newText) {
    friendListAdapter.getFilter().filter(newText);

    return true;
}

フィルタリングできるアダプター

  • Filterable実装されたBaseAdapterを使います。
  • 下記はアダプタープラス(FriendListAdapter)です。 https://github.com/erangaeb/dev-notes/blob/master/android-search-list/FriendListAdapter.java
  • フィルタリングするために、FriendFilterにカスタムフィルターを設定します。 ここで2つの配列リストを定義しています。 1つはリストビューでの表示用、もう1つはフィルタリング用のものです。
// original list, filtering do with this list
private ArrayList<User> friendList;

// filtered list construct by filtering the friendList
// it uses to create the list view
private ArrayList<User> filteredList;
  • 検索機能が使えるようになります。アウトプットのサンプルです。

プログラムでSearchViewを折りたたむ
* リストアイテムが選択された後に、新しいActivity ShareActivityにナビゲートします。
* ナビゲート中に、SearchViewを折りたたみます。

private void handelListItemClick(User user) {
    // close search view if its visible
    if (searchView.isShown()) {
        searchMenuItem.collapseActionView();
        searchView.setQuery("", false);
    }

    // pass selected user and sensor to share activity
    Intent intent = new Intent(this, ShareActivity.class);
    intent.putExtra("com.score.senzors.pojos.User", user);
    this.startActivity(intent);
    this.overridePendingTransition(R.anim.right_in, R.anim.stay_in);
}

検索クエリ入力中にポップアップテキストを表示する
* リスト表示のフィルタリングをONにします。
friendListView.setTextFilterEnabled(true);

  • onQueryTextChangeを下記のように設定します。 @Override
public boolean onQueryTextChange(String newText) {
    if (TextUtils.isEmpty(newText)) {
        friendListView.clearTextFilter();
    }
    else {
        friendListView.setFilterText(newText.toString());
    }

    return true;
}
  • これでsearchviewがポップアップして表示されます。これはそのままSearchViewに入録している文字がそのまま表示されます。

android

ソースコードの完全版はこちら
https://github.com/erangaeb/dev-notes/tree/master/android-search-list