i++

プログラム系のメモ書きなど

Android : SearchView に独自の CursorAdapter を設定する

幅広く独自のレイアウトで検索候補を表示できるようになるので使い勝手が良さそうです。

// bindView をオーバーライドしているので SimpleCursorAdapter のコンストラクタの String[] from は使っていない気がするのだが、null にすると動かない
mSearchView.setSuggestionsAdapter(
        new SimpleCursorAdapter(this, R.layout.search_suggestion_item,
                null,
                new String[] { BaseColumns._ID },
                null, 0) {

    @Override
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
        // constraint に SearchView に入力された文字列が入る
        if(constraint.length() == 0) {
            return null;
        }
        // 自前のデータベースなどを使ってカーソルを返す
        // 返すカーソルには BaseColumns._ID を含めること。
        return MyDb.getInstance(MainActivity.this).getSuggestions(constraint.toString());
    }

    @Override
    public void bindView(View view, Context context, Cursor cursor) {
        // view にはコンストラクタで指定した layout が inflate されたものが渡される。
        // view を変える場合は newView をオーバーライド。
        // cursor には runQueryOnBackgroundThread の結果の一行分。
        TextView suggestion_textview1 = (TextView) view.findViewById(R.id.search_suggestion_item_text1);
        String suggestion_text1 = cursor.getString(1);
        suggestion_textview1.setText(suggestion_text1);
    }
});

検索候補に使う Cursor の返し方については以下の記事なども参考に。

increment.hatenablog.com

Adding Custom Suggestions | Android Developers