Monday, 4 September 2017

SearchView Example in Android | How to implement Searching in Android

About Example:- Here is the example that "How to Use SearchView  in Android Application By using Coding"

Basic Requirement:-
1. MainActivity.java
2. activity_main.xml

Steps are:-
Step 1: Add a new project and open activity_main.xml and write following code:-

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
>
    <SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/search"
        android:layout_margin="20dp"
        android:iconifiedByDefault="false"
       
><requestFocus></requestFocus></SearchView>
    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/list"
></ListView>

</LinearLayout>

Step 2:- Now Open your MainActivity.java and add the  code will be like this:-
package com.example.supriyabharti.searchviewtest;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.SearchView;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends AppCompatActivity {
    SearchView searchView;
    ListView list;
    ArrayAdapter<String> adapter;
    String[] data={"India","Banglore","Bihar","Hyderabad","Delhi","Rajasthan","Goa","Hariyana","Chennai"};

    @Override    
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        list=(ListView)findViewById(R.id.list);
        searchView=(SearchView)findViewById(R.id.search);
        adapter=new ArrayAdapter<String>(getApplicationContext(),android.R.layout.simple_list_item_1,data);
        list.setAdapter(adapter);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override            
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override            
            public boolean onQueryTextChange(String newText) {
                String txt=newText;
                adapter.getFilter().filter(newText);
                return false;
            }
        });
    }
}


Output:-

No comments:

Post a Comment