Adv

Android Search RecyclerView

The concept we are exploring here is:

  • Searching or Filtering a recyclerview data

If you have more examples please post them below.

Share

Related Concepts

Adv

1 Example

  1. Android Custom RecyclerView with Images and Text Search/Filter

    Android Custom RecyclerView with Images and Text Search/Filter.

    This is an android tutorial to explore how to search or filter a recyclerview with images and text.

    The RecyclerView will comprise CardViews so it is the CardViews that we will be filtering.

    We use SearchView to input our search terms thus allowing us search in realtime.

    Let’s go.

    1. Create Basic Activity Project

    1. First create a new project in android studio. Go to File –> New Project.
    2. Type the application name and choose the company name.
      New Project Dialog
    3. Choose minimum SDK.
      Choose minimum SDK
    4. Choose Basic activity.
      Choose Empty Activity
    5. Click Finish.
      Finish

    Basic activity will have a toolbar and floating action button already added in the layout

    Normally two layouts get generated with this option:

    No. Name Type Description
    1. activity_main.xml XML Layout Will get inflated into MainActivity Layout.Typically contains appbarlayout with toolbar.Also has a floatingactionbutton.
    2. content_main.xml XML Layout Will be included into activity_main.xml.You add your views and widgets here.
    3. MainActivity.java Class Main Activity.

    In this example I used a basic activity.

    The activity will automatically be registered in the android_manifest.xml. Android Activities are components and normally need to be registered as an application component.

    If you’ve created yours manually then register it inside the <application>...<application> as following, replacing the MainActivity with your activity name:

            <activity android_name=".MainActivity">
    
                <intent-filter>
    
                    <action android_name="android.intent.action.MAIN" />
    
                    <category android_name="android.intent.category.LAUNCHER" />
    
                </intent-filter>
    
            </activity>

    You can see that one action and category are specified as intent filters. The category makes our MainActivity as launcher activity. Launcher activities get executed first when th android app is run.

    Advantage of Creating Basic Activity project

    You can optionally choose empty activity over basic activity for this project.

    However basic activity has the following advantages:

    No. Advantage
    1. Provides us a readymade toolbar which gives us actionbar features yet easily customizable
    2. Provides us with appbar layout which implements material design appbar concepts.
    3. Provides a FloatinActionButton which we can readily use to initiate quick actions especially in examples like these.
    4. Decouples our custom content views and widgets from the templating features like toolbar.

    Generated Project Structure

    AndroidStudio will generate for you a project with default configurations via a set of files and directories.

    Here are the most important of them:

    No. File Major Responsibility
    1. build/ A directory containing resources that have been compiled from the building of application and the classes generated by android tools. Such a tool is the R.java file. R.java file normally holds the references to application resources.
    2. libs/ To hold libraries we use in our project.
    3. src/main/ To hold the source code of our application.This is the main folder you work with.
    4. src/main/java/ Contains our java classes organized as packages.
    5. src/main/res/ Contains our project resources folders as follows.
    6. src/main/res/drawable/ Contains our drawable resources.
    7. src/main/res/layout/ Contains our layout resources.
    8. src/main/res/menu/ Contains our menu resources XML code.
    9. src/main/res/values/ Contains our values resources XML code.These define sets of name-value pairs and can be strings, styles and colors.
    10. AndroidManifest.xml This file gets autogenerated when we create an android project.It will define basic information needed by the android system like application name,package name,permissions,activities,intents etc.
    11. build.gradle Gradle Script used to build the android app.

    2. Build.Gradle(App level)

    This is our app level(located in app folder) build.gradle. We are not using any third party libraries instead we add some support libraries.

    dependencies {
        compile fileTree(dir: 'libs', include: ['*.jar'])
        testCompile 'junit:junit:4.12'
        compile 'com.android.support:appcompat-v7:23.2.1'
        compile 'com.android.support:design:23.2.1'
        compile 'com.android.support:cardview-v7:23.2.1'
        compile 'com.android.support:recyclerview-v7:23.2.1'
    }

    3. Create User Interface

    User interfaces are typically created in android using XML layouts as opposed by direct java coding.

    This is an example fo declarative programming.

    ######### Advantages of Using XML over Java

    No. Advantage
    1. Declarative creation of widgets and views allows us to use a declarative language XML which makes is easier.
    2. It’s easily maintanable as the user interface is decoupled from your Java logic.
    3. It’s easier to share or download code and safely test them before runtime.
    4. You can use XML generated tools to generate XML

    Here are our layouts for this project:

    (a). activity_main.xml
    • This layout gets inflated to MainActivity user interface.
    • It includes the content_main.xml.

    Here are some of the widgets, views and viewgroups that get employed”

    No. View/ViewGroup Package Role
    1. CordinatorLayout android.support.design.widget Super-powered framelayout that provides our application’s top level decoration and is also specifies interactions and behavioros of all it’s children.
    2. AppBarLayout android.support.design.widget A LinearLayout child that arranges its children vertically and provides material design app bar concepts like scrolling gestures.
    3. ToolBar <android.support.v7.widget A ViewGroup that can provide actionbar features yet still be used within application layouts.
    4. FloatingActionButton android.support.design.widget An circular imageview floating above the UI that we can use as buttons.
    <?xml version="1.0" encoding="utf-8"?>
    <android.support.design.widget.CoordinatorLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_fitsSystemWindows="true"
        tools_context="com.tutorials.hp.customrecyclerfiltering.MainActivity">
    
        <android.support.design.widget.AppBarLayout
            android_layout_width="match_parent"
            android_layout_height="wrap_content"
            android_theme="@style/AppTheme.AppBarOverlay">
    
            <android.support.v7.widget.Toolbar
                android_id="@+id/toolbar"
                android_layout_width="match_parent"
                android_layout_height="?attr/actionBarSize"
                android_background="?attr/colorPrimary"
                app_popupTheme="@style/AppTheme.PopupOverlay" />
    
        </android.support.design.widget.AppBarLayout>
    
        <include layout="@layout/content_main" />
    
        <android.support.design.widget.FloatingActionButton
            android_id="@+id/fab"
            android_layout_width="wrap_content"
            android_layout_height="wrap_content"
            android_layout_gravity="bottom|end"
            android_layout_margin="@dimen/fab_margin"
            android_src="@android:drawable/ic_dialog_email" />
    
    </android.support.design.widget.CoordinatorLayout>
    (b). content_main.xml

    This layout gets included in your activity_main.xml.
    We add our SearchView on to of our RecyclerView here.

    The SearchView will be used to Filter the RecyclerView.

    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout 
        
        
        android_layout_width="match_parent"
        android_layout_height="match_parent"
        android_paddingBottom="@dimen/activity_vertical_margin"
        android_paddingLeft="@dimen/activity_horizontal_margin"
        android_paddingRight="@dimen/activity_horizontal_margin"
        android_paddingTop="@dimen/activity_vertical_margin"
        app_layout_behavior="@string/appbar_scrolling_view_behavior"
        tools_context="com.tutorials.hp.customrecyclerfiltering.MainActivity"
        tools_showIn="@layout/activity_main">
    
        <LinearLayout
            android_layout_width="match_parent"
            android_orientation="vertical"
            android_layout_height="match_parent">
    
            <android.support.v7.widget.SearchView
                android_id="@+id/mSearch"
                android_layout_width="match_parent"
                android_layout_height="50dp"
                app_defaultQueryHint="Search.."
                ></android.support.v7.widget.SearchView>
    
            <android.support.v7.widget.RecyclerView
                android_id="@+id/myRecycler"
                android_layout_width="wrap_content"
                android_layout_below="@+id/mSearch"
                android_layout_height="wrap_content"
                class="android.support.v7.widget.RecyclerView" />
    
        </LinearLayout>
    </RelativeLayout>
    (c). model.xml

    This is a CardView with various widgets. This layout will represent a single item in our RecyclerView:

    <?xml version="1.0" encoding="utf-8"?>
    <android.support.v7.widget.CardView 
        android_orientation="horizontal" android_layout_width="match_parent"
        
        android_layout_margin="5dp"
        card_view_cardCornerRadius="10dp"
        card_view_cardElevation="5dp"
    
        android_layout_height="match_parent">
    
        <RelativeLayout
            android_layout_width="match_parent"
            android_layout_height="match_parent">
    
            <ImageView
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_id="@+id/playerImage"
                android_padding="10dp"
                android_src="@drawable/herera" />
    
            <TextView
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_textAppearance="?android:attr/textAppearanceLarge"
                android_text="Name"
                android_id="@+id/nameTxt"
                android_padding="10dp"
                android_layout_alignParentTop="true"
                android_layout_toRightOf="@+id/playerImage" />
    
            <TextView
                android_layout_width="wrap_content"
                android_layout_height="wrap_content"
                android_textAppearance="?android:attr/textAppearanceMedium"
                android_text="Position"
                android_id="@+id/posTxt"
                android_padding="10dp"
                android_layout_alignBottom="@+id/playerImage"
                android_layout_alignParentRight="true" />
    
        </RelativeLayout>
    </android.support.v7.widget.CardView>

    4. Player.java

    This is our data object. Our POJO class.

    This class represents a single Player.

    package com.tutorials.hp.customrecyclerfiltering;
    
    public class Player {
    
        private String name;
        private String pos;
        private int img;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getPos() {
            return pos;
        }
    
        public void setPos(String pos) {
            this.pos = pos;
        }
    
        public int getImg() {
            return img;
        }
    
        public void setImg(int img) {
            this.img = img;
        }
    }

    5. ItemClickListener.java

    This an interface to define for us our event handler signature.

    package com.tutorials.hp.customrecyclerfiltering;
    
    import android.view.View;
    
    public interface ItemClickListener {
    
        void onItemClick(View v,int pos);
    }

    6. MyHolder.java

    This is a ViewHolder class.

    It will hold our inflated model.xml as a view object for recycling. This View will be used by the MyAdapter class.

    package com.tutorials.hp.customrecyclerfiltering;
    
    import android.support.v7.widget.RecyclerView;
    import android.view.View;
    import android.widget.ImageView;
    import android.widget.TextView;
    
    public class MyHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    
        //OUR VIEWS
        ImageView img;
        TextView nameTxt,posTxt;
    
        ItemClickListener itemClickListener;
    
        public MyHolder(View itemView) {
            super(itemView);
    
            this.img= (ImageView) itemView.findViewById(R.id.playerImage);
            this.nameTxt= (TextView) itemView.findViewById(R.id.nameTxt);
            this.posTxt= (TextView) itemView.findViewById(R.id.posTxt);
    
            itemView.setOnClickListener(this);
        }
    
        @Override
        public void onClick(View v) {
            this.itemClickListener.onItemClick(v,getLayoutPosition());
    
        }
    
        public void setItemClickListener(ItemClickListener ic)
        {
            this.itemClickListener=ic;
        }
    }

    7. MyAdapter.java

    This is our RecyclerView.Adapter class.

    This class will first inflate our model.xml and bind data to the resultant view.

    This class will also implement the android.widget.Filterable interface.

    package com.tutorials.hp.customrecyclerfiltering;
    
    import android.content.Context;
    import android.support.design.widget.Snackbar;
    import android.support.v7.widget.RecyclerView;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.Filter;
    import android.widget.Filterable;
    
    import java.util.ArrayList;
    
    public class MyAdapter extends RecyclerView.Adapter<MyHolder> implements Filterable{
    
        Context c;
        ArrayList<Player> players,filterList;
        CustomFilter filter;
    
        public MyAdapter(Context ctx,ArrayList<Player> players)
        {
            this.c=ctx;
            this.players=players;
            this.filterList=players;
        }
    
        @Override
        public MyHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            //CONVERT XML TO VIEW ONBJ
            View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.model,null);
    
            //HOLDER
            MyHolder holder=new MyHolder(v);
    
            return holder;
        }
    
        //DATA BOUND TO VIEWS
        @Override
        public void onBindViewHolder(MyHolder holder, int position) {
    
            //BIND DATA
            holder.posTxt.setText(players.get(position).getPos());
            holder.nameTxt.setText(players.get(position).getName());
            holder.img.setImageResource(players.get(position).getImg());
    
            //IMPLEMENT CLICK LISTENET
            holder.setItemClickListener(new ItemClickListener() {
                @Override
                public void onItemClick(View v, int pos) {
                    Snackbar.make(v,players.get(pos).getName(),Snackbar.LENGTH_SHORT).show();
                }
            });
    
        }
    
        //GET TOTAL NUM OF PLAYERS
        @Override
        public int getItemCount() {
            return players.size();
        }
    
        //RETURN FILTER OBJ
        @Override
        public Filter getFilter() {
            if(filter==null)
            {
                filter=new CustomFilter(filterList,this);
            }
    
            return filter;
        }
    }

    8. CustomFilter.java

    This class will derive from android.widget.Filter class.

    This is the class that will search our data.

    package com.tutorials.hp.customrecyclerfiltering;
    
    import android.widget.Filter;
    
    import java.util.ArrayList;
    
    public class CustomFilter extends Filter{
    
        MyAdapter adapter;
        ArrayList<Player> filterList;
    
        public CustomFilter(ArrayList<Player> filterList,MyAdapter adapter)
        {
            this.adapter=adapter;
            this.filterList=filterList;
    
        }
    
        //FILTERING OCURS
        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            FilterResults results=new FilterResults();
    
            //CHECK CONSTRAINT VALIDITY
            if(constraint != null && constraint.length() > 0)
            {
                //CHANGE TO UPPER
                constraint=constraint.toString().toUpperCase();
                //STORE OUR FILTERED PLAYERS
                ArrayList<Player> filteredPlayers=new ArrayList<>();
    
                for (int i=0;i<filterList.size();i++)
                {
                    //CHECK
                    if(filterList.get(i).getName().toUpperCase().contains(constraint))
                    {
                        //ADD PLAYER TO FILTERED PLAYERS
                        filteredPlayers.add(filterList.get(i));
                    }
                }
    
                results.count=filteredPlayers.size();
                results.values=filteredPlayers;
            }else
            {
                results.count=filterList.size();
                results.values=filterList;
    
            }
    
            return results;
        }
    
        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {
    
           adapter.players= (ArrayList<Player>) results.values;
    
            //REFRESH
            adapter.notifyDataSetChanged();
        }
    }

    9. MainActivity.java

    This is our main activity. It derives from android.app.Activity.

    This activity will use the inflated activity_main.xml as the UI view.

    package com.tutorials.hp.customrecyclerfiltering;
    
    import android.os.Bundle;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.DefaultItemAnimator;
    import android.support.v7.widget.LinearLayoutManager;
    import android.support.v7.widget.RecyclerView;
    import android.support.v7.widget.SearchView;
    import android.support.v7.widget.Toolbar;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    
    import java.util.ArrayList;
    
    public class MainActivity extends AppCompatActivity {
    
       SearchView sv;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            setSupportActionBar(toolbar);
    
            FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
            fab.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                            .setAction("Action", null).show();
                }
            });
    
            sv= (SearchView) findViewById(R.id.mSearch);
            RecyclerView rv= (RecyclerView) findViewById(R.id.myRecycler);
    
            //SET ITS PROPETRIES
            rv.setLayoutManager(new LinearLayoutManager(this));
            rv.setItemAnimator(new DefaultItemAnimator());
    
            //ADAPTER
            final MyAdapter adapter=new MyAdapter(this,getPlayers());
            rv.setAdapter(adapter);
    
            //SEARCH
            sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
                @Override
                public boolean onQueryTextSubmit(String query) {
                    return false;
                }
    
                @Override
                public boolean onQueryTextChange(String query) {
                    //FILTER AS YOU TYPE
                    adapter.getFilter().filter(query);
                    return false;
                }
            });
    
        }
    
        //ADD PLAYERS TO ARRAYLIST
        private ArrayList<Player> getPlayers()
        {
            ArrayList<Player> players=new ArrayList<>();
            Player p=new Player();
            p.setName("Ander Herera");
            p.setPos("Midfielder");
            p.setImg(R.drawable.herera);
            players.add(p);
    
            p=new Player();
            p.setName("David De Geaa");
            p.setPos("Goalkeeper");
            p.setImg(R.drawable.degea);
            players.add(p);
    
            p=new Player();
            p.setName("Michael Carrick");
            p.setPos("Midfielder");
            p.setImg(R.drawable.carrick);
            players.add(p);
    
            p=new Player();
            p.setName("Juan Mata");
            p.setPos("Playmaker");
            p.setImg(R.drawable.mata);
            players.add(p);
    
            p=new Player();
            p.setName("Diego Costa");
            p.setPos("Striker");
            p.setImg(R.drawable.costa);
            players.add(p);
    
            p=new Player();
            p.setName("Oscar");
            p.setPos("Playmaker");
            p.setImg(R.drawable.oscar);
            players.add(p);
    
            return players;
        }
    }

    Download

    [sociallocker id=8131]

    Resource Link
    GitHub Browse Browse
    GitHub Download Link [download id=”8195″ template=”pmpro_button”]

    [/sociallocker]

    Best Regards,
    Oclemy.




Share an Example

Share an Example

Browse
What is the capital of Egypt? ( Cairo )