1/ Design The 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_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<SearchView
android:background="@color/white"
android:id="@+id/searchViewId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:queryHint="Search"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<ListView
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/ MainActivity- Used a listView to show data.
package com.tutorialb.searchviewfromarraylist;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ListView listView;
SearchView search_bar;
ArrayAdapter<String> adapter;
ArrayList<String> countryList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EdgeToEdge.enable(this);
setContentView(R.layout.activity_main);
ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main), (v, insets) -> {
Insets systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars());
v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom);
return 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 = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, countryList);
listView.setAdapter(adapter);
search_bar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override
public boolean onQueryTextSubmit(String query) {
adapter.getFilter().filter(query);
return false;
}
@Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
});
}
}
3/ Run and See the output