How to change the layout of a RecyclerView? - Lists and Grids
A RecyclerView
is a more advanced and flexible version of ListView. To create a simple RecyclerView
, we need to create a model, view and adapter to initialize the list. Apart from this, a RecyclerView
also needs a layout manager to position the items in the list. With a layout manager, the list will not be displayed. So always remember to initialise the RecyclerView with a layout manager
To simply put it, a layout manager positions items inside a RecyclerView
and determines when to reuse item views that are no longer visible to the user.
RecyclerView
provides these built-in layout managers:
LinearLayoutManager
shows items in a vertical or horizontal scrolling list.GridLayoutManager
shows items in a grid.StaggeredGridLayoutManager
shows items in a staggered grid.
LinearLayoutManager
The simplest layout manager is the LinearLayoutManager. To use it, you simply have to create a new instance of this manager and set it to the RecyclerView.
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new LinearLayoutManager(this));
GridLayoutManager
GridLayoutManager has more than one item in each row and each item in a row has the same height. It is different from LinearLayoutManager in that it takes two variables, the context and the no. of items in each row of the grid. For example, the Google Play Music app has 2 items in each row of the Grid Layout.
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new GridLayoutManager(this, 2));
StaggeredGridLayoutManager
StaggeredGridLayoutManager is also similar GridLayoutManager. However, each item in the grid do not have the same height. This gives the effect of a staggered grid.
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recycler_view); recyclerView.setLayoutManager(new StaggeredGridLayoutManager(this, 2));
GridLayoutManager & StaggeredGridLayoutManager are very useful for dynamically changing the view from a grid to a list by just changing the number of items in a row to 1 for list view and to 2 or more for grid view.