【问题标题】:RecyclerView does not change from 2 columns to 3 columns when phone is rotated旋转手机时RecyclerView不会从2列变为3列
【发布时间】:2017-05-25 18:45:06
【问题描述】:

当我将视图旋转到横向时,RecyclerView 不会从两列切换到三列。我试过这段代码:

mGLManager.setSpanCount(3);

mGLManager = (GridLayoutManager)mRecyclerView.getLayoutManager();
mGLManager.setSpanCount(2);
mRecyclerView.setLayoutManager(mGLManager);

mRecyclerView.setLayoutManager( new GridLayoutManager(MainActivity.this, 3) );

我也尝试了这些行来让它刷新:

mRecyclerView.refreshDrawableState();

mAdapter.notifyDataSetChanged();

mRecyclerView.invalidate();

mRecyclerView.requestLayout();

mRecyclerView.swapAdapter(mRecyclerView.getAdapter(), true);
mRecyclerView.scrollBy(0,0);

这是我当前的代码。

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

        // set the number of columns based on the orientation
        if( newConfig.orientation == Configuration.ORIENTATION_PORTRAIT ) {
            mRecyclerView.setLayoutManager( new GridLayoutManager(MainActivity.this, 2));
            mRecyclerView.invalidate();
            Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
        } else if( newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE ) {
            mRecyclerView.setLayoutManager( new GridLayoutManager(MainActivity.this, 3));
            mRecyclerView.invalidate();
            Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
        }
    }

祝酒词表明当我翻转方向时代码运行。感谢您的帮助!

【问题讨论】:

    标签: android android-recyclerview gridlayoutmanager


    【解决方案1】:

    在 Activity 的 onCreateView 方法中添加,每次方向更改时都会调用它

    if(getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT){
     mRecycler.setLayoutManager(new GridLayoutManager(MainActivity.this, 2));
    }
    else{
     mRecycler.setLayoutManager(new GridLayoutManager(MainActivity.this, 3));
      }
    

    【讨论】:

    • 感谢您的回答。我必须用 if 块包装它: if( mGLManager != null ) { // 你的代码——谢谢!此外,onCreate 方法在手机每次旋转时都会运行,所以我也必须更新 onCreate 方法。感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-05-18
    • 2022-01-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-02
    相关资源
    最近更新 更多