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));
}
}
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));
}