RecyclerView
What is RecyclerView?
It is a library which use to creates dynamic the elements when they are needed. RecyclerView recycles it’s individual elements, when you scroll down RecyclerView doesn’t destroy its view, it is reusing it for a different element.
Classes work together to build dynamic list in RecyclerView:
1- Add RecyclerView to the layout we want to use it in. 2- RecyclerView.ViewHolder: Each element in the list is defined by a view holder object, RecyclerView binds holder to its data. 3- RecyclerView.Adapter: RecyclerView needs the Adapter to bind thw data to each ViewHolder. 4- LayoutManager: to arranges the individual elements in your list.
Implementing your RecyclerView:
Before starting you need to do the following:
1- Decide what the list or grid is going to look like.
2- Design how each element in the list is going to look and behave.
3- Define the Adapter that associates your data with the ViewHolder views.
Implementing adapter.
-
The
AdaptercreatesViewHolderobjects and also binding to it. -
When we define the adapter, we need to override the following: 1- onCreateViewHolder():
RecyclerViewcalls this method to create newViewHolder.
2- onBindViewHolder(): RecyclerView calls this method to bind a ViewHolder with data
3- getItemCount(): RecyclerView calls this method to get the size of the data list.
Example of Adapter:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.ViewHolder> {
private String[] localDataSet;
/**
* Provide a reference to the type of views that you are using
* (custom ViewHolder).
*/
public static class ViewHolder extends RecyclerView.ViewHolder {
private final TextView textView;
public ViewHolder(View view) {
super(view);
// Define click listener for the ViewHolder's View
textView = (TextView) view.findViewById(R.id.textView);
}
public TextView getTextView() {
return textView;
}
}
/**
* Initialize the dataset of the Adapter.
*
* @param dataSet String[] containing the data to populate views to be used
* by RecyclerView.
*/
public CustomAdapter(String[] dataSet) {
localDataSet = dataSet;
}
// Create new views (invoked by the layout manager)
@Override
public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
// Create a new view, which defines the UI of the list item
View view = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.text_row_item, viewGroup, false);
return new ViewHolder(view);
}
// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, final int position) {
// Get element from your dataset at this position and replace the
// contents of the view with that element
viewHolder.getTextView().setText(localDataSet[position]);
}
// Return the size of your dataset (invoked by the layout manager)
@Override
public int getItemCount() {
return localDataSet.length;
}
}