Changing number of columns with GridLayoutManager and RecyclerView

fapps picture fapps · Apr 11, 2015 · Viewed 60.4k times · Source

Inside my fragment I'm setting my GridLayout in the following way: mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));

So, I just want to change that 2 for a 4 when the user rotates the phone/tablet. I've read about onConfigurationChanged and I tried to make it work for my case, but it isn't going in the right way. When I rotate my phone, the app crashes...

Could you tell me how to solve this issue?

Here is my approach to find the solution, which is not working correctly:

  @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);

        int orientation = newConfig.orientation;

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

Thanks in advance!

Answer

TWiStErRob picture TWiStErRob · Oct 1, 2015

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
}