【问题标题】:RecycleView/CardView data set updateRecyclerView/CardView 数据集更新
【发布时间】:2014-10-13 02:10:34
【问题描述】:

我目前正在尝试在 AsyncTask 完成操作后更新 RecyclerView

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Initializing RecycleView
    mRecyclerView = (RecyclerView)findViewById(R.id.list);
    mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    mRecyclerView.setItemAnimator(new DefaultItemAnimator());

    mAdapter = new AdvertAdapter(this.results, R.layout.card_advert, this);
    mRecyclerView.setAdapter(mAdapter);

这是我AsyncTask的代码sn-p:

    @Override
    protected void onPostExecute(String result){
        // your stuff
        listener.onTaskCompleted(data);
    }

在监听器 Activity 类中,我正在更新数据集并尝试通知我的自定义适配器数据集已更改:

@Override
public void onTaskCompleted(ArrayList<Data>results) {
    this.results = results;
    this.mAdapter.notifyDataSetChanged();
    System.out.println("Done.");
}

notifyDataSetChanged() 似乎实际上并没有做任何事情,因为即使在最后一行之后,列表仍然是空的。通过调试器,我可以验证结果确实包含正确的结果,并且 onTaskCompleted 正在主线程上运行。如何使用新结果更新我的RecyclerView

【问题讨论】:

    标签: android android-asynctask android-5.0-lollipop android-cardview


    【解决方案1】:

    我认为您应该将ArrayList&lt;Data&gt;results 添加到您的适配器数据中。

    类似这样的:

    @Override
    public void onTaskCompleted(ArrayList<Data>results) {
        //this.results = results;
    
        this.mAdapter.clear();
        this.mAdapter.add(results);
        //or this.mAdapter.results = results;
    
        this.mAdapter.notifyDataSetChanged();
        System.out.println("Done.");
    }
    

    【讨论】:

    • 如果我正在更新特定的回收站项目,上述内容是否适用但使用“this.mAdapter.notifyItemChanged(getAdapterPosition())”?或 "this,mAdapter.notifyItemChanged(position)" where position = getAdapterPosition()?
    猜你喜欢
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-19
    • 2021-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多