Changing number of columns with GridLayoutManager and RecyclerView
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));
}
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
}