BLOGs
Android Development
Published February 02nd, 2017 by

How To Decorate Recycler View Items In Android – Tutorial

RecyclerView is much like ListView in android. Both are used to display the listing in android application but they differ in some cases compared to each other. ListView is somewhat slower compared to RecyclerView. RecyclerView provides some additional customization that ListView does not provide. RecyclerView is introduced in Material Design in android but it can also be used in backward compatibility applications. RecyclerView can optimize the performance of the application by recycling the views to display row items because it uses the same view to display each list item where ListView created the new view every time the list item is visible.

ListView have some limitation for its list item, while RecyclerView provides the special tool to design the list item. We can also say that RecyclerView is the new version of ListView in android. ListView provides the list item customization with the help of drawable resource but its customization is limited for example we can use the drawable for list item which is same for all the items in list, it cannot provide customization for a specific list item. While recyclerview’s ItemDecoration tool provides the customization of special drawing and layout design for a specific list item. ItemDecoration provides customization of dividers, highlights design, grouping of list item in RecyclerView.

recycler view

ItemDecoration provides the customization for specific list item for example if we need such dividers for list item where last list item does not need dividers than it is possible by using ItemDecoration of recyclerview. With using ItemDecoration we can easily modify the appearance of list items in our recyclerview. Using ItemDecoration we can identify and get the position of first and last list item.

ItemDecoration is an abstract class of RecyclerView which allows us to add custom decoration to each and every item in RecyclerView. Here we will use this class to create our custom decoration class by extending RecyclerView.ItemDecoration. We will use this class to customize dividers of our list items.

Dependency:

RecyclerView is a part of android support library so before using we will need to add the recyclerview’s dependency in our build.gradle file to use the view in our application as describe below.

dependencies {
    .......

    compile 'com.android.support:recyclerview-v7:23.0.0'

}

Layout Design:

For using ItemDecoration we will need a RecyclerView in our layout so main activity’s layout file look like below.

layout/activity_main.xml :

<RelativeLayout

    xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:paddingBottom="@dimen/activity_vertical_margin"

    android:paddingLeft="@dimen/activity_horizontal_margin"

    android:paddingRight="@dimen/activity_horizontal_margin"

    android:paddingTop="@dimen/activity_vertical_margin"

    tools:context="com.example.recyclerviewdecorationdemo.MainActivity">


    <android.support.v7.widget.RecyclerView

        android:id="@+id/recycler_view"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"/>

</RelativeLayout>

The layout contains the recyclerview we can put other views also as our need. We also need list item layout to display the items in our recyclerview so below is our list item’s layout.

Layout/list_row.xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"

              android:orientation="vertical"

              android:padding="16dp"

              android:layout_width="match_parent"

              android:layout_height="wrap_content">

    <TextView

        android:id="@+id/list_item"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:textColor="@android:color/black"/>

</LinearLayout>

To customize the list item we also need drawable resource on which we can do our customization. We can also use android’s default drawables. So below is our divider’s drawable resource file.

Drawable/divider_background.xml:

<shape xmlns:android="http://schemas.android.com/apk/res/android"

       android:shape="rectangle">

    <size android:height="1dp" />

    <solid android:color="#ff4BB484" />

</shape>

We will use this drawable file in our custom decoration class.

Custom Decoration Class:

We will extend the RecyclerView.ItemDecoration class to apply the customization on list item inside recyclerview. This class will be called in our activity after setting adapter to recyclerview.

DividerItemDecoration.java

public class DividerItemDecoration extends RecyclerView.ItemDecoration {

    private static final int[] ATTRS = new int[]{android.R.attr.listDivider};

    private Drawable mDivider;




    public DividerItemDecoration(Context context) {

        final TypedArray styledAttributes = context.obtainStyledAttributes(ATTRS);

        mDivider = styledAttributes.getDrawable(0);

        styledAttributes.recycle();

    }




    public DividerItemDecoration(Context context, Drawable drawable) {

        mDivider = drawable;

    }

    @Override

    public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {

        int left = parent.getPaddingLeft();

        int right = parent.getWidth() - parent.getPaddingRight();

        int childCount = parent.getChildCount();

        for (int i = 0; i < childCount; i++) {

            View child = parent.getChildAt(i);

            RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child.getLayoutParams();

            int top = child.getBottom() + params.bottomMargin;

            int bottom = top + mDivider.getIntrinsicHeight();

            mDivider.setBounds(left, top, right, bottom);

            mDivider.draw(c);

        }

    }

}

In above java class we have extends RecyclerView.ItemDecoration class to allow us provide it’s overridden methods. ItemDecoration class provides three different methods. First is onDraw, it will allows us to draw items on the canvas which are drawn before all the items in the recyclerview. Second is onDrawOver, it will allows us to draw items on the canvas which are drawn after the items in the recyclerview. Third is getItemOffsets, it will allow us the ability to set items at the given positions in recyclerview. Here we have used onDraw method to explain the simple usage to ItemDecoration class.

Note that we have two constructors in our custom class. First constructor will use the default drawable of android system. Other one will use the custom drawable class that we have created previously. While using default drawable, we cannot modify the color or other properties of our divider. So we have our custom drawable resource to modify some properties for our dividers.

The Activity:

After creating our custom decoration class its time to use it in our application. So below is our main activity with ItemDecoration implemented.

MainActivity.java :

public class MainActivity extends AppCompatActivity {

    String data[] = {"India","Australia","Japan","China","France","Germany","Russia","England","New Zealand","Africa"};

    RecyclerView recyclerView;

    CountryAdapter countryAdapter;

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        recyclerView = (RecyclerView)findViewById(R.id.recycler_view);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));

        countryAdapter = new CountryAdapter(data);

        recyclerView.setAdapter(countryAdapter);

        recyclerView.addItemDecoration(new DividerItemDecoration(this,getResources().getDrawable(R.drawable.divider_background)));

    }




    public class CountryAdapter extends RecyclerView.Adapter<CountryAdapter.ViewHolder> {

        String[] countryList;

        public CountryAdapter(String[] countries) {

            this.countryList = countries;

        }

        @Override

        public int getItemCount() {

            return countryList.length;

        }

        @Override

        public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_row,parent, false);

            return new ViewHolder(v);

        }

        @Override

        public void onBindViewHolder(ViewHolder holder, int position) {

            holder.countryText.setText(countryList[position]);

        }

        public class ViewHolder extends RecyclerView.ViewHolder {

            public TextView countryText;

            public ViewHolder(View view) {

                super(view);

                countryText = (TextView)view.findViewById(R.id.list_item);

            }

        }

    }

}

As we can see that we have an array of strings to display name of Countries in our recyclerview. We have also created our custom recyclerview adapter named CountryAdapter to set the data in our recyclerview. Inside onCreate method we have the reference of our recyclerview from layout file which we have created previously. After taking the reference we have set the adapter so our recyclerview will be filled with the data. After setting adapter we have added our custom decoration using addItemDecoration(…) method passing the object of our custom DividerItemDecoration. It will draw our custom divider in every list item of recyclerview  accept last list item.

Application Screens :

1

This article is written by expert for the android development community. The team of Android app development India has explained about decorating Recycler View Items In in this tutorial. If you have any question or queries, please feel free to ask.

Rosina De Palma
Follow Me

Rosina De Palma

Technical Writer at Nex Mobility
I write technical articles especially for iOS, Android and Xamarin mobile app development. Analyse on Cross Platform Apps and interested to learn android app development.
Rosina De Palma
Follow Me

Our rankings are completely independent, transparent, and community driven; they are based on user reviews and client sentiment. These android development companies had to earn their way up and didn't just pay their way up.

View Rankings of Best Android Development Companies