Skip to main content

SearchView Widget in Android

Android SearchView widget, users enter search queries and can then submit a request for the search provider offers search user interface. This survey shows a list of suggestions or proposals, or to launch into the existing results and users will allow you to get the result.
wolaris-searchview-widget-in-android

Configuring the search widget

Basic XML
<android.support.v7.widget.SearchView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Hello World!" />
Search widget provides the same functionality as the search dialog. It has been operating in accordance with the user to perform a search, and it can search suggestions and voice search. Action Bar will search widget not an option for you, instead of you can put the layout of the search widget on the ground.
Create new android project
Configure dependencies. add follow code
dependencies {
    // Other dependencies ....

    compile 'com.android.support:recyclerview-v7:25.2.0'
    compile 'com.android.support:cardview-v7:25.2.0'

    // ....
}
Open in res > layout activity_main.xml file, add following code
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    android:orientation="vertical"
    tools:context="com.wolaris.widget.searchview.MainActivity">

    <android.support.v7.widget.CardView
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <android.support.v7.widget.SearchView
                android:id="@+id/searchView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"/>

            <android.support.v7.widget.RecyclerView
                android:id="@+id/recyclerView"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:background="@color/cardview_light_background"/>

        </LinearLayout>

    </android.support.v7.widget.CardView>

</LinearLayout>
Create new xml file named text_row_item.xml
text_row_item.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="50dp"
    android:background="#30000000">

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:textSize="16sp"
        android:layout_marginTop="1px"
        android:paddingLeft="@dimen/activity_horizontal_margin"
        android:paddingRight="@dimen/activity_horizontal_margin"
        android:background="@color/cardview_light_background"
        android:gravity="center_vertical"/>
</FrameLayout>
Create new java file named Singer
Here we have a constructor for setting the singer name and a function to get the singer name.
Singer.java
package com.wolaris.widget.searchview;

public class Singer {
    String name;

    public Singer(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
Create new java file named CustomAdapter and add following code
Provide views to RecyclerView with data from SingerList.
CustomAdapter.java
package com.wolaris.widget.searchview;

import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
    private static final String TAG = "CustomAdapter";

    private List<Singer> mDataset;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        private final TextView textView;

        public ViewHolder(View v) {
            super(v);

            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Log.d(TAG, "Element " + getAdapterPosition() + " clicked.");
                }
            });
            textView = (TextView) v.findViewById(R.id.textView);
        }

        public TextView getTextView() {
            return textView;
        }
    }

    public CustomAdapter(List<Singer> dataSet) {
        mDataset = dataSet;
        arraylist = dataSet;
    }

    @Override
    public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
        View v = LayoutInflater.from(viewGroup.getContext())
                .inflate(R.layout.text_row_item, viewGroup, false);
        return new ViewHolder(v);
    }

    public void onBindViewHolder(ViewHolder viewHolder, final int position) {
        Log.d(TAG, "Element " + position + " set.");
        viewHolder.getTextView().setText(mDataset.get(position).getName());
    }

    @Override
    public int getItemCount() {
        return mDataset.size();
    }
        
    public void add(Singer string) {
        insert(string, mDataset.size());
    }
    
    public void insert(Singer string, int position) {
        mDataset.add(position, string);
        notifyItemInserted(position);
    }

    public void clear() {
        int size = mDataset.size();
        mDataset.clear();
        notifyItemRangeRemoved(0, size);
    }

    public void addAll(List<Singer> strings) {
        int startIndex = mDataset.size();
        mDataset.addAll(startIndex, strings);
        notifyItemRangeInserted(startIndex, strings.size());
    }
}
Open src > package > MainActivity.java and add following code
In this step we open MainActivity and add the code to initiate SearchView and RecyclreView. In this we create an Singer name list and then set the adapter to fill the data in RecyclreView. In this we also implement SearchView.OnQueryTextListener to filter the singerlist according to search query.
MainActivity.java
package com.wolaris.widget.searchview;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.util.Log;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "SearchViewActivity";

    protected RecyclerView mRecyclerView;
    protected CustomAdapter mAdapter;
    protected RecyclerView.LayoutManager mLayoutManager;
    private ArrayList<Singer> singerList;
    private ArrayList<Singer> arraylist;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        singerList = new ArrayList<>();
        singerList.add(new Singer("Ed Sheeran"));
        singerList.add(new Singer("Bruno Mars"));
        singerList.add(new Singer("Alan Walker"));
        singerList.add(new Singer("G-Eazy"));
        singerList.add(new Singer("The Chainsmaoker"));
        singerList.add(new Singer("Clean Bandit"));
        singerList.add(new Singer("Martin Garrix"));
 
        arraylist = new ArrayList<>();
        arraylist.addAll(singerList);

        SearchView searchView = (SearchView) findViewById(R.id.searchView);
        searchView.setIconifiedByDefault(false);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                newText = newText.toLowerCase();
                mAdapter.clear();
                if (newText.length() == 0) {
                    mAdapter.addAll(arraylist);
                } else {
                    for (Singer singer : arraylist) {
                        if (singer.getName().toLowerCase().contains(newText)) {
                            mAdapter.add(singer);

                        }
                    }
                }
                Log.e(TAG, newText);
                return false;
            }
        });

        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);

        mLayoutManager = new LinearLayoutManager(this);
        mRecyclerView.setLayoutManager(mLayoutManager);
        mRecyclerView.scrollToPosition(0);

        mAdapter = new CustomAdapter(singerList);
        mRecyclerView.setAdapter(mAdapter);
    }
}

Popular posts from this blog

Single Page Application With Laravel 5.3 And Vue.js 2.1.x

Description: Single Page Application With Laravel 5.3 And Vue.js 2.1.x Single Page Application with Laravel 5.3 and Vue.js 2.1.x. Refer the source code for better understanding. Frameworks and Libraries: - Laravel 5.3 - Vue.js 2.1.x - Vue Router - axios Provides: - CRUD - Single Page Application - Pagination - Sorting by columns - Advance filter - Filter relations - - - Source Code: https://github.com/codekerala/spa-laravel-vuejs - - - You should follow Code .

Laravel 5.4 With Android Firebase Cloud Messaging (FCM)

DOWNLOAD How to Package Aenean lacinia A library that lets you create a beer styled progress view with bubbles and all! (hic). Beer Progress View A cool beer styled progress view with realistic bubbles*. Cheers! Increment progress. Change beer colour. Change wave size. Change bubble colour. (*realism of bubbles not guaranteed) Setup To use BeerProgressView in your projects, simply add the library as a dependency to your build. Gradle dependencies { compile 'uk.co.barbuzz:beerprogressview:0.0.4' } Maven <dependency> <groupId>uk.co.barbuzz.beerprogressview</groupId> <artifactId>beerprogressview</artifactId> <version>0.0.4</version> <type>pom</type> </dependency> Alternatively you can directly import the /library project into your Android Studio project and add it as a dependency in your build.gradle. The library is currently configur...

Apps created on Android

For applications on Android (for beginners) Start - for those of you who love DIY Android and the desire to create their own programs. The study of the application of decisions is not easy, but for a beginner it can be found. Some developers of applications for Android, to provide the tools to create applications for beginners, of course, these tools can be downloaded directly from Google Play on your Android gadget. Here are 5 tools manufacturers Android apps for beginners. 1. Appiventor Basically this program is used by inexperienced developers, and has now received belongs to the Massachusetts Institute of Technology. Tools such as this requires its own understands the language of a program or "coding", but do not worry, because this app also has video lessons. 2. PhoneGap For those of you who are effective using HTML, CSS or JavaScript simply using Fungab. Fungab not only used to create mobile applications for Android, but also for mobile phone application...