Skip to content Skip to sidebar Skip to footer

How To Add Fixed Button In Recyclerview Adapter?

nav_draw_row.xml

Solution 1:

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:

privateboolean hasLoadButton = true;

publicbooleanisHasLoadButton() {
    return hasLoadButton;
}

publicvoidsetHasLoadButton(boolean hasLoadButton) {
    this.hasLoadButton = hasLoadButton;
    notifyDataSetChanged();
}

@Overridepublic 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:

privatefinalintTITLE=0;
privatefinalintLOAD_MORE=1;
@OverridepublicintgetItemViewType(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) {
            returnnew MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.nav_draw_row, parent, false));
        } elseif (view type == LOAD_MORE) {
            returnnew MyViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.load_more_row, parent, false));
        } else {
            returnnull;
        }
    }

load_more_row

<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"><Buttonandroid: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 :

@OverridepublicvoidonBindViewHolder(MyViewHolder holder, int position) {
    if(position >= getItemCount()) {
        holder.loadMore....
    } else {
    NavDrawerItemcurrent= data.get(position);
    holder.title.setText(current.getTitle());
    }
}

Solution 2:

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

Post a Comment for "How To Add Fixed Button In Recyclerview Adapter?"