2
2

More than 3 years have passed since last update.

【Android】SearchView 使ってみた

Last updated at Posted at 2020-11-04

【Android】SearchView 使ってみた

SearchViewとは

文字を入力してもらうような検索レイアウトを作るのって、面倒だなと思ってたら、もともと用意されているレイアウトで、SearchViewというものがありました。

SearchViewについての公式ドキュメント

  • SearchViewの例

スクショ.png

使い方

使い方はとても簡単です。

  • レイアウト
searchView.xml
<androidx.appcompat.widget.SearchView
        android:id="@+id/search_view"
        // サイズはお任せで
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        // ヒントとして、文字入力部分に表示される文字列
        app:queryHint="キーワード検索"
        // 虫眼鏡の画像の表示・非表示を設定
        android:iconifiedByDefault="true"/>

現状で使いそうだと思ったリスナー

OnQueryTextListener

SearchViewに、文字が入力、または入力後に完了(検索)が行われた時のリスナークラス

  • 使い方の例
SampleActivity.kt
class SampleActivity : AppCompatActivity() {

  override fun onCreate(savedInstanceState: Bundle?) {
     val searchView = view.findViewById(R.id.search_view)
     searchView.setOnQueryTextListener(SearchViewListener())
  }

  // OnQueryTextListenerを、implementしたクラス
  class SearchViewListener(): OnQueryTextListener {
        // 入力された文字が変更された際に、呼ばれるメソッド
        override fun onQueryTextChange(newText: String?): Boolean {
            println("changed")
            return false
        }

        // 文字の入力後に、検索ボタンが押された際に呼ばれるメソッド
        override fun onQueryTextSubmit(query: String?): Boolean {
            println("done")
            return false
        }
  }
}

これで、何か文字が入力された時や、検索が押された時に、何かしらの処理が実行できます。

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