How to build a horizontal ListView with RecyclerView
I need to implement a horizontal listview in my Android application. I did a bit of research and came across How can I make a horizontal ListView in Android? and Horizontal ListView in Android?. However, these questions were asked before Recyclerview was released. Is there a better way to implement this now with Recyclerview?
Is there a better way to implement this now with RecyclerView now?
Yes.
When you use a RecyclerView
, you need to specify a LayoutManager
that is responsible for laying out each item in the view. The LinearLayoutManager
allows you to specify an orientation, just like a normal LinearLayout
would.
To create a horizontal list with RecyclerView
, you might do something like this:
LinearLayoutManager layoutManager
= new LinearLayoutManager(requireContext(), LinearLayoutManager.HORIZONTAL, false);
RecyclerView myList = (RecyclerView) findViewById(R.id.my_recycler_view);
myList.setLayoutManager(layoutManager);
<android.support.v7.widget.RecyclerView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
app:layoutManager="android.support.v7.widget.LinearLayoutManager" />