How to add dividers and spaces between items in RecyclerView?

 

In Android, you can add dividers and spaces between items in a RecyclerView by customizing the item decoration. You can create a custom ItemDecoration class that defines the spacing and dividers and then apply it to your RecyclerView. Here's an example of how to do this:

  1. Create a custom ItemDecoration class:

    Create a Java or Kotlin class that extends RecyclerView.ItemDecoration. This class will define the spacing and dividers between items.

    java
  • import android.content.Context; import android.graphics.Rect; import android.view.View; import androidx.annotation.NonNull; import androidx.recyclerview.widget.RecyclerView; public class CustomItemDecoration extends RecyclerView.ItemDecoration { private final int space; // Define the space (in pixels) between items public CustomItemDecoration(Context context, int space) { this.space = space; } @Override public void getItemOffsets(@NonNull Rect outRect, @NonNull View view, @NonNull RecyclerView parent, @NonNull RecyclerView.State state) { // Add space to the bottom of each item (except the last one) if (parent.getChildAdapterPosition(view) != parent.getAdapter().getItemCount() - 1) { outRect.bottom = space; } } }
  • Apply the ItemDecoration to your RecyclerView:

    In your activity or fragment where you have the RecyclerView, create an instance of your custom ItemDecoration class and add it to your RecyclerView.

    java
  • import android.os.Bundle; import androidx.appcompat.app.AppCompatActivity; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; public class MyActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_my); RecyclerView recyclerView = findViewById(R.id.recyclerView); recyclerView.setLayoutManager(new LinearLayoutManager(this)); // Create an instance of your custom ItemDecoration and add it to the RecyclerView int spacingInPixels = getResources().getDimensionPixelSize(R.dimen.spacing); // Define the spacing dimension recyclerView.addItemDecoration(new CustomItemDecoration(this, spacingInPixels)); // Set your RecyclerView adapter and data here // recyclerView.setAdapter(...); } }
  • Define the spacing dimension in your resources:

    In your res/values/dimens.xml file, define the spacing dimension that you want to use for spacing between items. For example:

    xml
    1. <resources> <dimen name="spacing">16dp</dimen> </resources>

      Adjust the spacing dimension as needed to control the space between items.

    With these steps, you've created a custom ItemDecoration class that adds spacing between items in your RecyclerView. You can also customize this class further to add dividers or adjust spacing based on your specific design requirements.

    Comments