Dol*_*rma 5 android android-fragments android-recyclerview
在我的应用程序中,我有这个代码来计算手机尺寸并将RecyclerView布局管理器更改为GridLayoutManager或LinearLayoutManager
private void changeFeedsLayout() {
// Choose between one, two or three elements per row
if (dpWidth > 720 && getResources().getConfiguration().orientation ==
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
instagram_feeds.setLayoutManager(new GridLayoutManager(
context, 3, LinearLayoutManager.VERTICAL, false));
} else if (dpWidth > 520) {
instagram_feeds.setLayoutManager(new GridLayoutManager(
context, 2, LinearLayoutManager.VERTICAL, false));
} else {
instagram_feeds.setLayoutManager(new LinearLayoutManager(
context, LinearLayoutManager.VERTICAL, false));
}
}
Run Code Online (Sandbox Code Playgroud)
当我将每个片段附加或提交到容器时,此代码工作正常MainActivity,但在更改手机方向时它不起作用,为了解决此问题,我使用此代码:
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
changeFeedsLayout();
}
Run Code Online (Sandbox Code Playgroud)
不幸的是,layoutmanagerRecyclerView总是LinearLayoutManager这样,我无法解决这个问题。打开其他片段并返回到上一个片段后工作正常。
更新
在更改手机方向时,此代码为:
instagram_feeds.setLayoutManager(new LinearLayoutManager(
context, LinearLayoutManager.VERTICAL, false));
Run Code Online (Sandbox Code Playgroud)
不适用于手机更改方向的changeFeedsLayout()方法,并且此方法无法在更改手机方向时正确计算手机尺寸
这可能听起来很奇怪,但这种情况唯一有效的解决方案是将这些设置放入资源中。Android 操作系统根据许多属性来获取资源,其中之一就是最小宽度。将列表与网格分开: values/bools.xml:
<resources>
<bool name="is_grid">false</bool>
</resources>
Run Code Online (Sandbox Code Playgroud)
另一个是values-sw520dp/bools.xml:
<resources>
<bool name="is_grid">true</bool>
</resources>
Run Code Online (Sandbox Code Playgroud)
对于列数相同的逻辑值-sw520dp/integers.xml:
<resources>
<integer name="grid_column_count">2</integer>
</resources>
Run Code Online (Sandbox Code Playgroud)
和values-sw720dp/integers.xml:
<resources>
<integer name="grid_column_count">3</integer>
</resources>
Run Code Online (Sandbox Code Playgroud)
所以在代码中这将是这样的:
if (getResources().getBoolean(R.bool.is_grid)) {
instagram_feeds.setLayoutManager(new GridLayoutManager(getActivity(), getResources().getInteger(R.integer.grid_column_count));
} else {
instagram_feeds.setLayoutManager(new LinearLayoutManager(getActivity());
}
Run Code Online (Sandbox Code Playgroud)
这应该在您创建视图时应用,无需处理配置更改 - 它已经为您完成了。让操作系统完成它的工作。
| 归档时间: |
|
| 查看次数: |
1636 次 |
| 最近记录: |