android - RecyclerView 旋转时为空
问题描述
我从这里学到了如何防止在方向更改 时重新启动如何在 Android 上的方向更改时避免重新启动活动
因此我实现了它
在我的清单中,我确保旋转不会触发重启
android:configChanges="keyboardHidden|orientation|screenSize"
我的布局很简单
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/scroll">
<android.support.v7.widget.RecyclerView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/list_of_items"/>
</ScrollView>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="@+id/add"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
在我的 MainActivity 我设置
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
setContentView(R.layout.activity_main);
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView itemsView = findViewById(R.id.list_of_items);
itemsView.setLayoutManager(new LinearLayoutManager(this));
itemsView.setNestedScrollingEnabled(false);
ItemsAdapter items = new ItemsAdapter(this);
itemsView.setAdapter(items);
}
每当发生旋转时,我都会检查onConfigurationChanged
项目计数和可见性状态,并打印出回收站视图是可见的并且它包含 x 个项目,但不知何故在旋转时它永远不会显示这些项目。我错过了什么?我的 ItemsAdapter 是一个非常简单的适配器,里面没有任何花哨的东西。
解决方案
通过setContentView(R.layout.activity_main)
在您的设备中使用,您onConfigurationChanged()
基本上每次旋转设备时都会创建新视图。但是您只设置了一次适配器,用于您在onCreate()
. 删除此行onConfigurationChanged()
应该可以解决您的问题。
顺便说一句,你很可能需要 ScrollView,RecyclerView 处理它自己的滚动。
推荐阅读
- php - Gutenberg:如何根据编辑器中的块更改排版选择器大小(编辑器字体大小)?
- kotlin - 桌面版 Kotlin 多平台的 http 请求
- linux - “sudo whoami”和“sudo who am i”有什么区别?
- android - 如何在我的 android 应用程序上在 kotlin 中实现 SearchView?
- linux - 使用 POSIX 版本的 tar(不是 GNU 版本)时,是否可以替换 tar 中的 -P 选项?
- shell - 在 shell 脚本中查找给定数字的友好数字
- spring - 在 IntelliJ 中创建 Spring Boot 应用程序后立即出错
- c# - 在 .NET Core API 5 中不使用 IdentityUser(和 IdentityRoles)创建 JWT 身份验证
- java - Android没有为相对布局设置动画
- shared-libraries - 如何使用已编译的库