有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java屏幕旋转适配器notifyDataSetChanged不工作

我在旋转屏幕时更新RecyclerView时遇到问题。通过点击fab按钮,我显示了带有输入字段的对话框片段。然后,当我旋转屏幕并保存数据时,我的RecyclerView不会更新。我正在onCreate方法中设置适配器。我应该再次轮换,以便看到新的数据。如何解决这个问题

提前谢谢

dataSource = new MyBusinessDataSource(this);

        try
        {
            dataSource.openForRead();
        }
        catch (SQLException sqlEx)
        {
            Toast.makeText(MyBusinessMainActivity.this, R.string.sqlite_exception, Toast.LENGTH_SHORT).show();
            return;
        }

        categories = dataSource.getAllCategories();

        adapter = new CategoriesAdapter(this, categories);
        rv_list_cats.setAdapter(adapter);
        dataSource.close();

共 (1) 个答案

  1. # 1 楼答案

    您需要在活动或片段中重写onConfigurationChanged方法,并在其中更新数据。比如

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if(adapter!=null)
        {
            categories = dataSource.getAllCategories();
            adapter.notifyDataSetChanged();
        }
    }
    

    此外,如果清单中没有使用ScreenConfig属性,请使用如下所示的选项

       android:configChanges="orientation|screenSize"