phone 旋转时 RecyclerView 不会从 2 列变为 3 列

RecyclerView does not change from 2 columns to 3 columns when phone is rotated

当我将视图旋转为横向时,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();
        }
    }

toasts 表明代码在我翻转方向时运行。感谢您的帮助!

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

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