当手机旋转时,RecyclerView 不会从 2 列变为 3 列

Bir*_*man 1 android gridlayoutmanager android-recyclerview

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

mGLManager.setSpanCount(3);

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

mRecyclerView.setLayoutManager( new GridLayoutManager(MainActivity.this, 3) );
Run Code Online (Sandbox Code Playgroud)

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

mRecyclerView.refreshDrawableState();

mAdapter.notifyDataSetChanged();

mRecyclerView.invalidate();

mRecyclerView.requestLayout();

mRecyclerView.swapAdapter(mRecyclerView.getAdapter(), true);
mRecyclerView.scrollBy(0,0);
Run Code Online (Sandbox Code Playgroud)

这是我当前的代码。

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();
        }
    }
Run Code Online (Sandbox Code Playgroud)

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

sas*_*mar 5

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

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