【Android】SearchView 使ってみた
SearchViewとは
文字を入力してもらうような検索レイアウトを作るのって、面倒だなと思ってたら、もともと用意されているレイアウトで、SearchViewというものがありました。
- SearchViewの例
使い方
使い方はとても簡単です。
- レイアウト
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
}
}
}
これで、何か文字が入力された時や、検索が押された時に、何かしらの処理が実行できます。