Changing number of columns with GridLayoutManager and RecyclerView Changing number of columns with GridLayoutManager and RecyclerView android android

Changing number of columns with GridLayoutManager and RecyclerView


If you have more than one condition or use the value in multiple places this can go out of hand pretty fast. I suggest to create the following structure:

res  - values    - dimens.xml  - values-land    - dimens.xml

with res/values/dimens.xml being:

<?xml version="1.0" encoding="utf-8"?><resources>    <integer name="gallery_columns">2</integer></resources>

and res/values-land/dimens.xml being:

<?xml version="1.0" encoding="utf-8"?><resources>    <integer name="gallery_columns">4</integer></resources>

And the code then becomes (and forever stays) like this:

final int columns = getResources().getInteger(R.integer.gallery_columns);mRecycler.setLayoutManager(new GridLayoutManager(mContext, columns));

You can easily see how easy it is to add new ways of determining the column count, for example using -w500dp/-w600dp/-w700dp resource folders instead of -land.

It's also quite easy to group these folders into separate resource folder in case you don't want to clutter your other (more relevant) resources:

android {    sourceSets.main.res.srcDir 'src/main/res-overrides' // add alongside src/main/res}


Try handling this inside your onCreateView method instead since it will be called each time there's an orientation change:

if(getActivity().getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){     mRecycler.setLayoutManager(new GridLayoutManager(mContext, 2));}else{     mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));}


A more robust way to determine the no. of columns would be to calculate it based on the screen width and at runtime. I normally use the following function for that.

public static int calculateNoOfColumns(Context context) {    DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();    float dpWidth = displayMetrics.widthPixels / displayMetrics.density;    int scalingFactor = 200; // You can vary the value held by the scalingFactor    // variable. The smaller it is the more no. of columns you can display, and the    // larger the value the less no. of columns will be calculated. It is the scaling    // factor to tweak to your needs.    int columnCount = (int) (dpWidth / scalingFactor);    return (columnCount>=2?columnCount:2); // if column no. is less than 2, we still display 2 columns}

It is a more dynamic method to accurately calculate the no. of columns. This will be more adaptive for users of varying screen sizes without being resticted to only two possible values.

NB: You can vary the value held by the scalingFactor variable. The smaller it is the more no. of columns you can display, and the larger the value the less no. of columns will be calculated. It is the scaling factor to tweak to your needs.