RecyclerView无法正确更新

时间:2015-04-21 22:13:36

标签: android material-design android-recyclerview

我正确使用RecyclerView吗?每当我更新数据时,即使修改了数据集并调用了相关的notify方法,视图仍会显示旧数据。最重要的是,我没有看到任何动画,所以我一定做错了。

以下是相关的代码片段:

private void refreshData() {
    Utils.hideSoftKeyboard(this);
    if (!Utils.isOnline(getApplicationContext())) {
        Toast.makeText(getApplicationContext(), R.string.toast_no_conn, Toast.LENGTH_SHORT).show();
        return;
    }
    String stopNumber = mStopEdit.getText().toString();
    if (stopNumber.isEmpty()) {
        Toast.makeText(getApplicationContext(), R.string.toast_no_stop, Toast.LENGTH_SHORT).show();
        return;
    }
    mResultNoStop.setVisibility(View.GONE);
    mResults.setVisibility(View.GONE);
    mProgressCircle.setVisibility(View.VISIBLE);
    if (!mDataset.isEmpty()) {
        int size = mDataset.size();
        mDataset.clear();
        mAdapter.notifyItemRangeRemoved(0, size);
    }
    FiveT.getStopData(stopNumber, mRequestQueue, new FiveT.StopDataClientListener() {
        @Override
        public void onResponse(ApiResult result) {
            mProgressCircle.setVisibility(View.GONE);
            if (result.getStopResults().size() == 0) {
                mResultNoStop.setVisibility(View.VISIBLE);
                Toast.makeText(getApplicationContext(), R.string.toast_no_data, Toast.LENGTH_SHORT).show();
                return;
            }
            int i = 0;
            mStopName.setText(result.getStopName());
            for (StopResult res : result.getStopResults()) {
                mDataset.add(res);
                mAdapter.notifyItemInserted(i++);
            }
            mResults.setVisibility(View.VISIBLE);
        }
    });
}

编辑:我像这样初始化RecyclerView

mDataset = new ArrayList<StopResult>();
mRecyclerView = (RecyclerView) findViewById(R.id.results_recycler_view);
mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);
mAdapter = new RecyclerViewAdapter(mDataset, getApplicationContext());
mRecyclerView.setAdapter(mAdapter);

1 个答案:

答案 0 :(得分:1)

根据问题的评论:

在RecyclerView的初始化中,你在那里缺少的是项目动画师的设置。

根据你的代码:

mDataset = new ArrayList<StopResult>();

mRecyclerView = (RecyclerView) findViewById(R.id.results_recycler_view);
mRecyclerView.setItemAnimator(new MyItemAnimator());

mLayoutManager = new LinearLayoutManager(this);
mRecyclerView.setLayoutManager(mLayoutManager);

mAdapter = new RecyclerViewAdapter(mDataset, getApplicationContext());
mRecyclerView.setAdapter(mAdapter);

您可以参考this库,以便找到最适合您需求的动画。