【发布时间】:2015-06-17 06:10:44
【问题描述】:
在我的片段中,我通过以下方式设置我的 GridLayout:
mRecycler.setLayoutManager(new GridLayoutManager(rootView.getContext(), 2));
所以,我只想在用户旋转手机/平板电脑时将 2 更改为 4。我已经阅读了有关onConfigurationChanged 的信息,并试图让它适用于我的情况,但它的方式并不正确。当我旋转手机时,应用程序崩溃...
你能告诉我如何解决这个问题吗?
这是我找到解决方案的方法,但无法正常工作:
@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));
}
}
提前致谢!
【问题讨论】:
-
请添加崩溃日志
-
我刚刚查看了我的 logcat,但这并没有导致崩溃。但它仍然无法正常工作。
-
我不会创建新的经理,而是使用现有的经理。在您的 recyclerview 上使用 getLayoutManager(),将其转换为 GridLayoutManager。在该经理调用 setSpanCount(orientation == Portrait ? 2 : 4) 并且为了重绘视图调用 adaper.notifyDatasetChanged() 如果您的视图不是每次都重绘,这应该可以正常工作。
-
哇!这听起来像是我在寻找,但我不知道如何实现。我会尝试并告诉你。
-
请注意,在创建视图本身时检查方向总是一个好主意。您通常在活动的 onCreate 或片段的 onCreateView 中执行此操作。确保您这样做,因为您的用户可能会以横向模式启动活动
标签: android android-orientation android-gridlayout android-recyclerview