【发布时间】:2018-08-20 03:39:03
【问题描述】:
我从这里学到了如何防止在方向改变时重新启动 How to avoid restarting activity when orientation changes on 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 是一个非常简单的适配器,里面没有任何花哨的东西。
【问题讨论】:
-
通过在您的
onConfigurationChanged()中使用setContentView(R.layout.activity_main),您基本上每次旋转设备时都会创建新视图。但是您只需为在onCreate()中找到的视图设置一次适配器。从onConfigurationChanged()中删除这一行应该可以解决您的问题。顺便说一句,你很可能需要 ScrollView,RecyclerView 处理它自己的滚动。 -
@JanStoltman 如果您将其作为一个发布,我将接受它作为正确答案。成功了!!!
标签: android android-recyclerview android-orientation recyclerview-layout