Android RecyclerView with a SearchView with ItemClick
Their are mainly 8 files use in this project
1. src/MainActivity.java :-This MainActivity.java file used to add SearchView in RecyclerView and display filtered result.
2. res/layout/activity_main.xml :-activity_main.xml is the layout file(xml code of RecyclerView) of MainActivity.java.
3. res/layout/customitem.xml :-creating custom layout of image and text .
4. src/Item.java :-Generate Setter and getter here.
5. src/MainActivityAdapter.xml :-MainActivityAdatper.java is the adapter class of RecyclerView that is used in MainActivity.java class.
6. Src/drawable :-images store here that are used in app.
7.dependencies in build.gradle(Module:app)
Dependencies{
|
8. menu file searchfile.xml (res/menu/searchfile.xml )
<item
android:id="@+id/search" android:icon="@drawable/ic_search_white_24dp" android:orderInCategory="300" android:title="search here..." app:actionViewClass="android.support.v7.widget.SearchView" app:showAsAction="ifRoom|collapseActionView" /> |
Starting the code here -----
STEP 1. Create a new Project WRCSearchFilter in Android Studio.
STEP 2. Add this dependencies in build.gradle(Module:app) and then sync this library
Dependencies{
compile 'com.android.support:appcompat-v7:25.3.1' compile 'com.android.support:recyclerview-v7:25.3.1' compile 'com.android.support:cardview-v7:25.3.1' } |
STEP 3. save and Paste this images in res/drawable folder
Step 4.Create menu file searchfile.xml(res/menu/serachfile.xml)
Searchfile.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto"> <item android:id="@+id/search" android:icon="@drawable/ic_search_white_24dp" android:orderInCategory="300" android:title="search here..." app:actionViewClass="android.support.v7.widget.SearchView" app:showAsAction="ifRoom|collapseActionView" />
</menu>
|
STEP 5. Create java file Item.java
1. src/Item.java :- Generate Setter and getter here.
Item.java
package com.example.amitrawat.rcsearchfilter;
/** * Created by amit rawat on 11/27/2017. */public class Item {
private String name;
private int photo;
public Item(String name, int photo) {
this.name = name;
this.photo = photo;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPhoto() {
return photo;
}
public void setPhoto(int photo) {
this.photo = photo;
}
}
|
STEP 6. Create xml file customitem.xml
1. res/layout/customitem.xml :- creating custom layout of image and text .
Customitem.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:cardCornerRadius="10dp" app:cardUseCompatPadding="true"> <RelativeLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:padding="5dp"> <ImageView android:id="@+id/product_image" android:layout_width="100dp" android:layout_height="80dp" android:padding="0.75dp" android:scaleType="centerCrop" /> <TextView android:id="@+id/product_title" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:layout_toRightOf="@+id/product_image" android:text="title" android:textAppearance="?android:attr/textAppearanceSmall" /> </RelativeLayout> </android.support.v7.widget.CardView> |
STEP 7. Create java file MainActivityAdapter.xml
1. src/MainActivityAdapter.java :- MainActivityAdatper.java is the adapter class of RecyclerView that is used in MainActivity.java class.
MainActivityAdapter.java
package com.example.amitrawat.rcsearchfilter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/** * Created by amit rawat on 11/27/2017. */public class MainActivityAdapter extends
RecyclerView.Adapter<MainActivityAdapter.Holderview>{
private List<Item> productlist;
private Context context;
public MainActivityAdapter(List<Item> productlist, Context context) {
this.productlist = productlist;
this.context = context;
}
@Override public Holderview onCreateViewHolder(ViewGroup parent, int viewType) {
View layout= LayoutInflater.from(parent.getContext()).
inflate(R.layout.customitem,parent,false);
return new Holderview(layout);
}
@Override public void onBindViewHolder(Holderview holder, final int position) {
holder.v_name.setText(productlist.get(position).getName());
holder.v_image.setImageResource(productlist.get(position).getPhoto());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override public void onClick(View view) {
Toast.makeText(context, "click on " + productlist.get(position).getName(),
Toast.LENGTH_LONG).show();
}
});
}
@Override public int getItemCount() {
return productlist.size();
}
public void setfilter(List<Item> listitem)
{
productlist=new ArrayList<>();
productlist.addAll(listitem);
notifyDataSetChanged();
}
class Holderview extends RecyclerView.ViewHolder
{
ImageView v_image;
TextView v_name;
Holderview(View itemview)
{
super(itemview);
v_image=(ImageView) itemview.findViewById(R.id.product_image);
v_name = (TextView) itemView.findViewById(R.id.product_title);
}
}
}
|
STEP 8. Write code in java file MainActivity.java and xml file activity_main.xml
1.res/layout/activity_main.xml :-activity_main.xml is the layout file(xml code of RecyclerView) of MainActivity.java.
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:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="5dp" tools:context="com.example.amitrawat.rcsearchfilter.MainActivity"> <android.support.v7.widget.RecyclerView android:id="@+id/listshow" android:layout_width="match_parent" android:layout_height="match_parent" android:fadeScrollbars="true" /> </RelativeLayout> |
2 src/MainActivity.java :-This MainActivity.java file used to add SearchView in RecyclerView and display filtered result.
MainActivity.java
package com.example.amitrawat.rcsearchfilter;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SearchView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity {
SearchView searchView;
RecyclerView listshowrcy;
List<Item> productlists = new ArrayList<>();
MainActivityAdapter adapter;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//adding product name and image in array list of Item type
productlists.add(new Item("Harley Davidson Street 750 2016 Std",
R.drawable.harleydavidson));
productlists.add(new Item("Triumph Street Scramble 2017 Std",
R.drawable.streetscramble1));
productlists.add(new Item("Suzuki GSX R1000 2017 STD",
R.drawable.suzukigsx1000));
productlists.add(new Item("Suzuki GSX R1000 2017 R",
R.drawable.suzukigsx1000r));
productlists.add(new Item("Suzuki Gixxer 2017 SP",
R.drawable.suzukigixxer2017));
productlists.add(new Item("Suzuki Gixxer 2017 SF 2017 Fuel injected ABS",
R.drawable.suzukigixxer2017sf));
productlists.add(new Item("BMW R 1200 R 2017",
R.drawable.bmwr1200r));
productlists.add(new Item("BMW R 1200 RS 2017",
R.drawable.bmwr1200rs));
productlists.add(new Item("BMW R 1200 GSA 2017",
R.drawable.bmwr120gsa));
productlists.add(new Item("Royal Enfield Classic 350 2017 Gunmental Grey",
R.drawable.class350gungrey));
productlists.add(new Item("Honda MSX125 Grom 2018 STD",
R.drawable.hondagrom));
productlists.add(new Item("UM Motorcycles Renegade 2017 classic",
R.drawable.renegadecommandoclassic));
productlists.add(new Item("Ducati Scrambler 2017 Mach 2.0",
R.drawable.scramblermach));
productlists.add(new Item("yamaha Fazer 2017 25",
R.drawable.yamahafazer));
listshowrcy = (RecyclerView) findViewById(R.id.listshow);
listshowrcy.setHasFixedSize(true);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
listshowrcy.setLayoutManager(linearLayoutManager);
adapter = new MainActivityAdapter(productlists, MainActivity.this);
listshowrcy.setAdapter(adapter);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.searchfile, menu);
final MenuItem myActionMenuItem = menu.findItem(R.id.search);
searchView = (SearchView) myActionMenuItem.getActionView();
changeSearchViewTextColor(searchView);
((EditText) searchView.findViewById(
android.support.v7.appcompat.R.id.search_src_text)).
setHintTextColor(getResources().getColor(R.color.white));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
@Override public boolean onQueryTextSubmit(String query) {
if (!searchView.isIconified()) {
searchView.setIconified(true);
}
myActionMenuItem.collapseActionView();
return false;
}
@Override public boolean onQueryTextChange(String newText) {
final List<Item> filtermodelist=filter(productlists,newText);
adapter.setfilter(filtermodelist);
return true;
}
});
return true;
}
private List<Item> filter(List<Item> pl,String query)
{
query=query.toLowerCase();
final List<Item> filteredModeList=new ArrayList<>();
for (Item model:pl)
{
final String text=model.getName().toLowerCase();
if (text.startsWith(query))
{
filteredModeList.add(model);
}
}
return filteredModeList;
}
//for changing the text color of searchview private void changeSearchViewTextColor(View view) {
if (view != null) {
if (view instanceof TextView) {
((TextView) view).setTextColor(Color.WHITE);
return;
} else if (view instanceof ViewGroup) {
ViewGroup viewGroup = (ViewGroup) view;
for (int i = 0; i < viewGroup.getChildCount(); i++) {
changeSearchViewTextColor(viewGroup.getChildAt(i));
}
}
}
}
}
|
ReplyDeleteGood afternoon, I'm trying to implement the SearchView, and everything merges well up to the call from the main class to setFiltre (), from the onQueryTextChange () method.
It tells me to change setFiltre to static or else it comes out as an error. Could you help me?
Concise code, very easy to understand, thankyou so much @programmingcodetech
ReplyDeletethank bro!
ReplyDelete