Mahdi Jafari
Mahdi Jafari

Reputation: 11

Adding empty space between items of RecyclerView with GridLayoutManager

I want to add empty spaces between items of a RecyclerView with GridLayoutManager but I can't find anything which solves my problem. I am creating a custom calendar and I have to make a custom grid from scratch. The first day of the month should be placed farther from the start when it is not the first day of the week.

I have achieved a similar result by passing a firstItemLocation to my RecyclerView adapter and overriding the onBindViewHolder method like this:

@Override
    public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
        if (position < firstItemLocation) {
            holder.itemView.setVisibility(View.GONE);
        } else {
            holder.tv.setText(String.format(Locale.US, "%d", list.get(position - firstItemLocation)));
        }
    }

It works fine but in a hypothetical situation when the user has to scroll it adds random empty spaces and glitches like this.

Any seggestions to make it better without that glitch?

Upvotes: 1

Views: 137

Answers (1)

snachmsm
snachmsm

Reputation: 19273

read about "recycling pattern", how it works and why - RecyclerView got its name because of this, so its very important to understand how this works

but in short:

inside onBindViewHolder you have to call desired methods ALWAYS. you are calling setVisibility only inside if and not in else. try with bellow snippet

    if (position < firstItemLocation) {
        holder.itemView.setVisibility(View.GONE);
        holder.tv.setText("")
    } else {
        holder.itemView.setVisibility(View.VISIBLE);
        holder.tv.setText(String.format(Locale.US, "%d", list.get(position - firstItemLocation)));
    }

thats because holder may be a "recycled" instance, used previously to draw another list item, and its set up is still applied to views

Upvotes: 1

Related Questions