class MainActivity : AppCompatActivity() {
lateinit var binding: ActivityMainBinding
lateinit var list: ArrayList<String>
lateinit var adapter: ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initData()
}
private fun initData() {
list = arrayListOf(
"test_duck",
"test_goose",
"test_chicken",
"a_duck",
"a_goose",
"a_chicken",
"b_duck",
"b_goose",
"b_chicken"
)
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, list)
binding.listView.adapter = adapter
binding.listView.isTextFilterEnabled = true
binding.searchView.setOnQueryTextListener(object : OnQueryTextListener {
override fun onQueryTextSubmit(query: String?): Boolean {
return false
}
override fun onQueryTextChange(newText: String?): Boolean {
if (!TextUtils.isEmpty(newText)) {
binding.listView.setFilterText(newText)
} else {
binding.listView.clearTextFilter()
}
return false
}
})
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<SearchView
android:id="@+id/searchView"
android:layout_width="match_parent"
android:layout_height="50dp"
android:iconifiedByDefault="false"/>
<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>