Introducion

A layout manager positions item views 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.

To create a custom layout manager, extend the RecyclerView.LayoutManager class.

 

Linear Layout Manager

It is used for displaying the data items in a horizontal or vertical scrolling List. In simple words we can say that we use the LinearLayoutManager for displaying RecyclerView as a ListView.

// Get the references
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext());

// Set a LinearLayoutManager with default orientation
recyclerView.setLayoutManager(linearLayoutManager);

// Set a LinearLayoutManager with horizontal orientation
linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(linearLayoutManager);

// Show the items from start to end
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getApplicationContext(),LinearLayoutManager.HORIZONTAL,false);
recyclerView.setLayoutManager(linearLayoutManager);

 

Grid Layout Manager

It is used to show the items in grid format.

// Get the reference of RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

// Set a GridLayoutManager with default vertical orientation and 3 number of columns
GridLayoutManager gridLayoutManager = new GridLayoutManager(getApplicationContext(),3);
recyclerView.setLayoutManager(gridLayoutManager);

// Set a GridLayoutManager with Horizontal orientation and 3 number of columns
gridLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL); // set Horizontal Orientation
recyclerView.setLayoutManager(gridLayoutManager);

 

Staggered Grid Layout Manager

t is used to show the items in staggered Grid.

// Get the reference of RecyclerView
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);

// Set a StaggeredGridLayoutManager with 3 number of columns and vertical orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);

// Set a StaggeredGridLayoutManager with 3 number of columns and horizontal orientation
StaggeredGridLayoutManager staggeredGridLayoutManager = new StaggeredGridLayoutManager(3, LinearLayoutManager.HORIZONTAL);
recyclerView.setLayoutManager(staggeredGridLayoutManager);