SearchView in Android

Hello friends,
Today we are going to learn about Searchview in android.
Using Search view we can search the data from the listview.
So without wasting time, let's go for the example.


activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <SearchView
        android:id="@+id/search"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:iconifiedByDefault="false"
        android:queryHint="Search Here" />

    <ListView
        android:id="@+id/data_list"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/search"
        android:divider="#ad5"
        android:dividerHeight="2dp" />
   
</RelativeLayout>



MainActivity.java

public class MainActivity extends AppCompatActivity {

    SearchView searchView;
    ListView datalist;
    ArrayList<String> arrayList;
    ArrayAdapter<String> arrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        searchView = (SearchView) findViewById(R.id.search);
        datalist = (ListView) findViewById(R.id.data_list);
        arrayList = new ArrayList<>();
        arrayList.add("Hacker");
        arrayList.add("Programmer");
        arrayList.add("Developer");
        arrayList.add("Designer");
        arrayList.add("SEO");
        arrayList.add("SMO");
        arrayList.add("Content Writer");
        arrayList.add("Java");
        arrayList.add("php");
        arrayList.add("android");
        arrayList.add("apple");
        arrayList.add("oppo");
        arrayList.add("vivo");
        arrayList.add("dell");
        arrayList.add("asus");
        arrayList.add("dell");
        arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
        datalist.setAdapter(arrayAdapter);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {

                if (arrayList.contains(query)) {
                    arrayAdapter.getFilter().filter(query);
                } else {
                    Toast.makeText(MainActivity.this, "No Data Found", Toast.LENGTH_LONG).show();
                }
                return false;
            }
            @Override
            public boolean onQueryTextChange(String newText) {
                //    adapter.getFilter().filter(newText);
                return false;
            }
        });
    }
}


OUTPUT:-





Comments