2
1

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 3 years have passed since last update.

SearchViewを利用したListView内の部分一致検索

Posted at

最初に

今回はSearchViewについて色々調べていたところ
意外とKotlinでのサイトが少なかったのともっと簡単にできそうだなというのがいくつかあったので備忘録として投稿させていただきます

ビュー

SearchViewの実装自体はすごく簡単でした

fragment_main.xml

<androidx.appcompat.widget.SearchView
        android:id="@+id/search"
        android:layout_width="0dp"
        android:layout_height="32dp"
        android:background="@color/colorPrimary"
        android:layout_marginTop="24dp"
        android:layoutDirection="rtl"
        app:searchHintIcon="@null"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toEndOf="parent"/>

これだけです
layoutDirectionは検索アイコンの位置を指定しています
今回は右寄せにしてありますデフォルトでは左寄せになっています
searchHintIconは検索を開始した際のヒントの部分のアイコンをどうするかの設定です今回はなしにしたいので@nullにしました

ListViewは配置すればいいだけでコードがメインなので省略させていただきます

コード

MainFragment.kt

private fun search(){
    val search = search
    val list = list
    val data = arrayOf("one","two","three","foo","five","six","seven","eight","nine","ten","eleven","twenty")
    var filter = arrayListOf<String>()
    val adapter = ArrayAdapter(requireContext(),android.R.layout.simple_list_item_1,data)
    val result = ArrayAdapter(requireContext(),android.R.layout.simple_list_item_1,filter)

    list.adapter = adapter

    search.setOnQueryTextListener(object : SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            return false
        }

        override fun onQueryTextChange(newText: String?): Boolean {
            val regex = Regex(newText.toString())
            result.clear()
            for (item in data.indices){
                if (regex.containsMatchIn(data[item])){
                    filter.add(data[item])
                }
            }
            list.adapter = result
            adapter.notifyDataSetChanged()
            return true
        }

    })
}

SearchViewにはsetOnQueryTextListenerというイベントリスナーがあります
onQueryTextChangeは入力文字が変更されるたびに呼び出されるメソッドです
onQueryTextSubmitは検索ボタンを押された際に呼び出されるメソッドです
検索結果を表示させたいタイミングによって処理を書くメソッドを変えるといいと思います

説明

処理自体も至ってシンプルです
Regexに入力された文字を代入してあげてそれをリストの中身と順番に比較していき別のArrayに追加してあげて表示させます
**result.clear()**を呼んであげないと前回の文字列での検索結果が残ったままになってしまうのでそのつどにclearをしてあげてください
**regex.containsMatchIn()**がない場合部分一致ではなくなってしまうのでご注意ください

最後に

今回はSearchViewを調べていたところもっとも使うであろうListViewでの実装や部分一致検索などがあまり詳しくは書いてなかったのでビギナーの方々に役立てばと思い書かせていただきました
次は何になるかはわかりませんが備忘録兼ビギナーのための何かになれば幸いです

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?