2017-05-25 44 views
0

当我将视图旋转到横向时,RecyclerView不会从两列切换到三列。我想这样的代码:当手机旋转时,RecyclerView不会从2列更改为3列

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

敬酒表明代码在我翻转方向时运行。谢谢你的帮助!

回答

1

添加您的活动onCreateView方法内将改变方向时

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

谢谢你的答案每次调用。如果(mGLManager!= null){ //你的代码 - 谢谢!我不得不用if包装它: if(mGLManager!= null) } 此外,每次手机旋转时都会运行onCreate方法,所以我必须更新onCreate方法。 感谢您的帮助! – Birdman