【发布时间】:2016-08-02 08:19:12
【问题描述】:
这是我遇到的一个非常奇怪的错误。
如果我像这样运行我的代码(向我的 recyclerview 添加一个新项目),它可以正常工作并更新:
mListOfData.add(someNewItem);
mRecyclerViewAdapter = new RecyclerViewAdapter(this, mListOfData);
mRecyclerViewAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mRecyclerViewAdapter);
但是如果我显示一个 Snackbar 告诉用户添加了一个项目,突然列表不会实时更新,除非我重新创建活动(旋转屏幕等):
View view = findViewById(R.id.primary_coordinator_layout);
mListOfData.add(someNewItem);
mRecyclerViewAdapter = new RecyclerViewAdapter(this, mListOfData);
mRecyclerViewAdapter.notifyDataSetChanged();
mRecyclerView.setAdapter(mRecyclerViewAdapter);
Snackbar.make(view, "Item added!", Snackbar.LENGTH_SHORT).show();
这可能是什么原因,或者如何防止它阻止视觉更新?
这是 XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<include
layout="@layout/toolbar_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
<android.support.design.widget.CoordinatorLayout
android:id="@+id/primary_coordinator_layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp">
<android.support.v7.widget.RecyclerView
android:id="@+id/recyclerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical" />
<TextView
android:id="@+id/emptytext"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
android:text="@string/no_items_in_recyclerview"
android:layout_gravity="center_horizontal"
android:gravity="center"/>
</LinearLayout>
<android.support.design.widget.FloatingActionButton
android:id="@+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_margin="@dimen/fab_margin"
android:src="@android:drawable/ic_input_add"/>
</android.support.design.widget.CoordinatorLayout>
</LinearLayout>
【问题讨论】:
标签: android xml android-recyclerview android-adapter android-snackbar