fapps fapps - 1 month ago 12x
Android Question

Changing number of columns with GridLayoutManager and RecyclerView

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
for a
when the user rotates the phone/tablet. I've read about
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:

public void onConfigurationChanged(Configuration 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!


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));
     mRecycler.setLayoutManager(new GridLayoutManager(mContext, 4));