DEV Community

Cover image for RecyclerView Last Item Extra Bottom Margin
K M Rejowan Ahmmed
K M Rejowan Ahmmed

Posted on • Edited on

3

RecyclerView Last Item Extra Bottom Margin

RecyclerView has been an everyday used item in Android App Development. During our use case, we often need some extra twists with the existing RecyclerView. One of them is to have some extra bottom margin for the last element of RecyclerView. Today, we'll try a good solution for that.

Solution

A good way to make this possible is to use LayoutParams in onBindViewHolder in the adapter class. We can set params for the last item and params for the rest of the items. The last item will have an extra bottom margin to achieve the goal.

Example Code

    @Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {

        if (position == list.size() - 1) {
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
            params.bottomMargin = 150; // last item bottom margin
            holder.itemView.setLayoutParams(params);

        } else {
            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
            params.bottomMargin = 10; // other items bottom margin
            holder.itemView.setLayoutParams(params);
        }

        // all other codes

    }
Enter fullscreen mode Exit fullscreen mode

Explanation

by position == last.size() - 1 we find out the last item of the list. And with the LayoutParams we set the bottom margin for the last item. And in the else section, we set the bottom margin for the rest of the items.
Now you know how to add an extra bottom margin to the last item to RecyclerView.

Find me on - Github, Facebook

More

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay