I am trying to change the number of columns that appear in the recycler view (grid layout) based on the display size. However I couldn't figure out a proper way of achieving it. At the moment I am using treeViewObserver
to change the number of columns based the change in screen size (during orientation). So if the app opens in portrait mode, number of columns (on the phone) it decides to be one, which look good but this method doesn't work when the app directly opens in landscape mode where a single streched out card in the grid is displayed on the screen.
Here recList is RecyclerView & glm is GridLayoutManager used in RecyclerView
viewWidth = recList.getMeasuredWidth();
cardViewWidthZZ = recList.getChildAt(0).getMeasuredWidth();
if (oldWidth == 0) {
oldWidth = cardViewWidthZZ;
}
if (oldWidth <= 0)
return;
int newSpanCount = (int) Math.floor(viewWidth / (oldWidth / 1.3f));
if (newSpanCount <= 0)
newSpanCount = 1;
glm.setSpanCount(newSpanCount);
glm.requestLayout();
Best Regards
You could create a screen dependent resource file and load it. A booleans.xml in values-w820p folder for example. Or possibly just create a layout for large screens and be done with it.
Here's my solution.
You can use it with either XML:
Or Java:
If you provide a fixed column width, you can extend
RecyclerView
and set the span count inonMeasure
accordingly:See my blog post for more info: http://blog.sqisland.com/2014/12/recyclerview-autofit-grid.html