使用GridLayoutManager和RecyclerView更改列数 [英] Changing number of columns with GridLayoutManager and RecyclerView

查看:779
本文介绍了使用GridLayoutManager和RecyclerView更改列数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在片段中,我通过以下方式设置GridLayout: mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));

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

因此,我只想在用户旋转手机/平板电脑时将2更改为4.我已经读过有关onConfigurationChanged的内容,并试图使其适用于我的情况,但是它的方向不正确.当我旋转手机时,应用程序崩溃了...

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

提前谢谢!

推荐答案

请尝试在onCreateView方法中处理此问题,因为每次更改方向时都会调用该方法:

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

这篇关于使用GridLayoutManager和RecyclerView更改列数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆