首页 > 解决方案 > 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 是一个非常简单的适配器,里面没有任何花哨的东西。

标签: androidandroid-recyclerviewandroid-orientationrecyclerview-layout

解决方案


通过setContentView(R.layout.activity_main)在您的设备中使用,您onConfigurationChanged()基本上每次旋转设备时都会创建新视图。但是您只设置了一次适配器,用于您在onCreate(). 删除此行onConfigurationChanged()应该可以解决您的问题。

顺便说一句,你很可能需要 ScrollView,RecyclerView 处理它自己的滚动。


推荐阅读