SearchView from ArrayList kotlin

04-Jan-2025

SearchView from ArrayList kotlin

Output:





1/  Modify activity_main.xml



<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:id="@+id/main"
android:layout_margin="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">


<SearchView
android:id="@+id/searchViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search"
android:background="@color/white"
style="@style/TextAppearance.Material3.SearchView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<ListView
android:layout_marginTop="8dp"
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_below="@+id/searchViewId"
app:layout_constraintTop_toBottomOf="@+id/searchViewId"/>


</RelativeLayout>



2/  Modify MainActivity.kt



package com.zissofworks.searchviewfromarraylistkotlin

import android.os.Bundle
import android.widget.ArrayAdapter
import android.widget.ListView
import android.widget.SearchView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat


class MainActivity : AppCompatActivity() {
lateinit var listView: ListView
lateinit var search_bar: SearchView
lateinit var adapter: ArrayAdapter<String>
val countryList: ArrayList<String> = ArrayList()


override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContentView(R.layout.activity_main)
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
insets
}

listView = findViewById(R.id.listView)
search_bar = findViewById(R.id.searchViewId)

countryList.add("Argentina")
countryList.add("Qatar")
countryList.add("Kuwait")
countryList.add("Bangladesh")
countryList.add("Saudi arabia")
countryList.add("Baharain")
countryList.add("Pakistan")
countryList.add("Nepal")

adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, countryList)
listView.adapter = adapter

search_bar.setOnQueryTextListener(object : SearchView.OnQueryTextListener{
override fun onQueryTextSubmit(query: String?): Boolean {
adapter.filter.filter(query)
return true
}

override fun onQueryTextChange(query: String?): Boolean {
adapter.filter.filter(query)
return true
}

})

}
}



Comments