Android RecyclerView Made Easy
android’s recyclerview consists of four things a recyclerView (declared in the xml layout), a row layout to inflate inside the recyclerview, an adapter declared in code and a layout manager also declared in code
the recyclerview is part of the support library so it needs to be added in the build.gradle (app module) file if haven’t added it yet
compile "com.android.support:recyclerview-v7:+"replace the “+” with the version you are using and it’s generally best to use the latest stable version
after you’ve added that line you can start using it, I’ll be using a single activity with one recyclerview
We’ll start in by adding a recycler view inside the activity_main.xml layout
Now we create a layout for the recyclerview to inflate
this layout is simple enough for our needs
i’ll be naming this layout recycler_item.xml (obviously you can name it to whatever you like)
now we create an adapter class that handles how the recyclerview inflates the item
now we go back to our main activity and add something to the adapter
now when we run the app it loads up a 100 textviews with our flashy pink background
what if we wanted to change the items inside the adapter ?
well we would just add a function inside the adapter
public void changeItems(List<String> items) {
this.items = items;
notifyDataSetChanged();
}what if we wanted to add items to it
well then we would add another function inside it
public void addItems(List<String> items) {
this.items.addAll(items);
notifyItemRangeInserted(this.items.size(), items.size());
}we can do more too
// this is how we'll clear all the items
public void clear() {
items.clear();
notifyDataSetChanged();
}//this is how we would insert a single item in a specific position
public void insertSingleItem(String s, int position){
items.add(s);
notifyItemInserted(position);
}
//this is how we would remove an item
public void removeItem( int position){
items.remove(position);
notifyItemRemoved(position);
}
and then we just call the function where we would need to for example I’m calling it on the main activity
rvAdapter.removeItem(3);we can also add a click listener inside the view holder so we can click on stuff
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
TextView textView;
public ViewHolder(View itemView) {
super(itemView);
textView = (TextView)
itemView.findViewById(R.id.textView);
textView.setOnClickListener(this);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.textView:
Toast.makeText(context, "text view clicked = " + getAdapterPosition(), Toast.LENGTH_SHORT).show();
break;
}
}
}now when we click on a textview it will display a toast containing the adapter position
in conclusion the recyclerview is extremely useful and relatively easy to implement, it’s a basic skill that every android dev needs to learn.
one important thing to remember is to change your data before calling onDatasetChanged() or bad things will happen.
