How to add a button at the end of RecyclerView?

I came across this problem and found this answer. The current selected answer is correct but it is missing some details. Here is the full implementation,

Add this method to your adapter

@Override
public int getItemViewType(int position) {
    return (position == myItems.size()) ? R.layout.button : R.layout.item;
}

It will check if the current position is past the last item in your list, if it is then it will return the button layout value to this method,

@Override
public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

    View itemView;

    if(viewType == R.layout.item){
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item, parent, false);
    }

    else {
        itemView = LayoutInflater.from(parent.getContext()).inflate(R.layout.button, parent, false);
    }

    return new MyViewHolder(itemView);
}

The above method checks if the passed viewType is the item layout or the button layout and then inflates the view occordingly and sends the inflated view to this method,

@Override
public void onBindViewHolder(MyViewHolder holder, int position) {
    if(position == myItems.size()) {
        holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(context, "Button Clicked", Toast.LENGTH_LONG).show();
            }
        });
    }
    else {
        final String name = myItems.get(position);
        holder.title.setText(name);
    }
}

This checks if we are past the last item in the list and if we are then it sets the onClick method to our button. Otherwise it creates an item like normal.

We also need to change the getItemCount method to this

@Override
public int getItemCount() {
    return myItems.size() + 1;
}

Since we are going through all the items and then adding a button at the end, the + 1 is our button.

Then lastly we need to add our view to the myViewHolder class

public class MyViewHolder extends RecyclerView.ViewHolder {
    public TextView title;
    public Button button;

    public MyViewHolder(View view) {
        super(view);
        title  = (TextView) view.findViewById(R.id.title);
        button = (Button) view.findViewById(R.id.bottom_button);
    }
}

I hope this helps!

Leave a Comment