2
4

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.

SeachView の使い方 - kotlin

Posted at

概要

テキストを入力すると検索結果がリアルタイムに変わる UI。
RecyclerView と一緒に使う。

RecyclerView の使い方 - kotlin

seach.xml

ヘッダーに使う menu を作る。

<?xml version="1.0" encoding="utf-8"?>
<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:title="search"
        android:icon="@drawable/ic_search_24dp"
        app:showAsAction="always|collapseActionView"
        app:actionViewClass="androidx.appcompat.widget.SearchView"/>
</menu>

MainActivity.kt

  • 先ほどの menu を紐づける
  • 検索バーの処理を書く

import androidx.appcompat.widget.SearchView

class MainActivity : AppCompatActivity() {
    var items:MutableList<String> = ArrayList()
    var seach_list:MutableList<String> = ArrayList()
    fun loadData(){
        items.add("item1")
        items.add("item2")
        items.add("item3")
        items.add("item4")
        seach_list.addAll(items)
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // RecyclerView のコードを書く
        
        loadData()
    }

    // メニューを紐付け
    override fun onCreateOptionsMenu(menu: Menu):Boolean{
        menuInflater.inflate(R.menu.search,menu)

        // 検索 UI のコード
        val seachItem = menu.findItem(R.id.menu_search)
        val searchView = seachItem.actionView as SearchView
        searchView.setOnQueryTextListener(object :SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                return true
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                if (newText!!.isNotEmpty()){
                    seach_list.clear()
                    val searchText = newText.toLowerCase()
                    items.forEach {
                        if (it.toLowerCase().contains(searchText))
                            seach_list.add(it)
                    }
                    item_list.adapter!!.notifyDataSetChanged()
                }else{
                    seach_list.clear()
                    seach_list.addAll(items)
                    item_list.adapter!!.notifyDataSetChanged()
                }
                return true
            }
        })
        return super.onCreateOptionsMenu(menu)
    }
}

参考

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?