Build a Load More Button into a recyclerview.
The first thing to do is to create a layout with your button and modify your viewhold to get the button id:
Then a simple way to make a button is to add +1 to the getItemCount() and a flag (i.e. boolean) to know if you need to draw the button.
The new getItemCount with the flag will look like this:
private boolean hasLoadButton = true;
public boolean isHasLoadButton() {
return hasLoadButton;
}
public void setHasLoadButton(boolean hasLoadButton) {
this.hasLoadButton = hasLoadButton;
notifyDataSetChanged();
}
@Override
public int getItemCount() {
if (hasLoadButton) {
return data.size() + 1;
} else {
return data.size();
}
}
Then you have to override into the adapter the method to get the type of the view:
private final int TITLE = 0;
private final int LOAD_MORE = 1;
@Override
public int getItemViewType(int position) {
if (position < getItemCount()) {
return TITLE;
} else {
return LOAD_MORE;
}
}
If the position is between 0 and data.size()-1, you will have a typeView for the title, else a typeview for the load more button.
Now we have to create the view holder:
In the method onCreateViewHolder(ViewGroup parent, int viewType),
@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (viewType == TITLE) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.nav_draw_row, parent, false));
} else if (view type == LOAD_MORE) {
return new MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.load_more_row, parent, false));
} else {
return null;
}
}
load_more_row
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:id="@+id/load_more"
android:text="load more !"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
Don't forget to change your viewholder to include the new button.
And finally the method onBindViewHolder :
@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
if(position >= getItemCount()) {
holder.loadMore....
} else {
NavDrawerItem current = data.get(position);
holder.title.setText(current.getTitle());
}
}
You can create a custom view that extends the recycler view class create linear layout add a button and a recycler view create class for the new view use your new custom view in XML and add the listener to the button and that's it hope that helps to give you an idea