【问题标题】:notifyDataSetChanged() doesn't worknotifyDataSetChanged() 不起作用
【发布时间】:2014-09-12 05:53:51
【问题描述】:

我昨天遇到了这个问题: 这里我有一个服务器返回的列表,列表中有一个Hashmap列表(List)和一个Hashmap。我遇到了两种情况,一种是当hashmap列表为空时,我在其中添加了一个新项目,然后调用 notifyDataSetChanged() 不起作用,另一种情况是当我更改 hashmap 中的值时,notifyDataSetChanged() 也没有刷新。我确定数据已成功更改。

它在 A 活动中显示,在 B 活动中更改数据。

一个活动:

protected List<CommentEntity> mDataList;
protected ListView mListView;
protected BaseListAdapter mAdapter;

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    int position = data.getIntExtra("position", -1);
    if (position > -1) {
        CommentEntity entity = (CommentEntity) data.getSerializableExtra(AppVars.Keys.EXTRA_ENTITY);
        mDataList.set(position, entity); // I want this list update
        mAdapter.notifyDataSetChanged();
    } else {
        // error
    }
}
public class BaseListAdapter extends BaseAdapter {

    @Override
    public int getCount() {
        return mDataList == null ? 0 : mDataList.size();
    }

    @Override
    public Object getItem(int position) {
        return mDataList == null ? null : mDataList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // actually this adapter is written in MyBaseFragment, and the child
        // Fragment will override setupItemView() method.it's working fine
        return setupItemView(position, convertView, parent);
    }
}

B活动:

private CommentEntity mCommentEntity;
// the list below is inside CommentEntity, QuoteEntity is extends HashMap<>.
private List<QuoteEntity> mQuoteList;
private QuoteAdapter mAdapter;
public void update(QuoteEntity newQuote) {
    mQuoteList.add(newQuote);
    mCommentEntity.setReplyRows(mQuoteList);
    mAdapter.notifyDataSetChanged();// This adapter is just working fine.
    setResult(-1, getIntent().putExtra(AppVars.Keys.EXTRA_ENTITY, mCommentEntity));
}

【问题讨论】:

  • 您如何设置mDataListmAdapter 以及它们之间的关系?
  • 感谢回复,我刚才忽略了,我现在添加它
  • 您需要更改适配器对象列表项,然后只有 notifyDAtasetchanged() 可以工作。您正在更改活动页面列表项
  • 谢谢,但列表与适配器有关。以及我尝试的许多方法,例如 listview.setAdapter(mAdapter = new BaseListAdapter()) 重新绑定数据,但不起作用
  • 这是迄今为止我见过的适配器最奇怪的写法。

标签: java android baseadapter notifydatasetchanged


【解决方案1】:

尝试重置列表视图而不是使用 notifyDataSetChanged();

           ListView lv = (ListView)FindViewById(R.id.lv);
           BaseListAdapter aa = new BaseListAdapter(//constructor's parameters);
           lv.setAdapter(aa);

【讨论】:

  • 你在 oncreate() 中初始化你的适配器和列表视图吗??
  • 如果你这样做了,那么只要你需要更新列表视图就调用 onCreate(null)
猜你喜欢
  • 2014-03-03
  • 1970-01-01
  • 2016-05-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-07
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多