BaseAdapter onItemClick引用旧实例

时间:2018-08-07 17:44:37

标签: android baseadapter

我有一个奇怪的问题,即在我的BaseAdapter中,当调用onClick时,如果我调用getItem(pos),则当前实例的listData是旧的;在回调中,如果我调用av.getAdapter()。getItem(pos),则会获取该项目的更新版本。经过数小时的调试,我不明白为什么会这样,有什么想法吗?请查看下面的代码,特别是onItemClick回调:

class MyAdapter extends BaseAdapter implements OnItemClickListener, IToggleChanged {

private final List<IItem> mData;

public MyAdapter(final Context context) {
    super();
    mData = new ArrayList<>();
    initData(context);
}

private void initData(final Context context) {
    mData.add(...);
    updateDataSet();
}

@Override
public boolean isEnabled(final int position) {
    return mData.get(position).isEnabled();
}

@Override
public int getCount() {
    return mData.size();
}

@Override
public Object getItem(final int pos) {
    return mData.get(pos);
}

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

private View inflateView(final Context context, final int pos) {
    final LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    return inflater.inflate(mData.get(pos).getLayoutId(), null);
}

@Override
public View getView(final int pos, final View view, final ViewGroup vg) {
    final View v = inflateView(vg.getContext(), pos);
    mData.get(pos).fillView(v);
    return v;
}

@Override
public void onItemClick(final AdapterView<?> av, final View view, final int pos, final long id) {

    // Scenario: toggle is off, you turn it on, list items get enabled, you now click on them and nothing happens because mEnabled=false, despite
    // we set it to true in updateDataSet. Don't know why this method have an old instance of mData, with the second method below it works as expected.
    //final IItem item2 = getItem(pos);

    final IItem item1 = av.getAdapter().getItem(pos);
    if (item1.isEnabled()) {
        item1.onClick(view);
    }
}

/**
 * Updates Items enable/disable state.
 */
private void updateDataSet() {
    for (final IItem item : mData) {
        item.setEnable(...);
    }
}

@Override
public void toggleChanged() {
    updateDataSet();
    notifyDataSetChanged();
}

}

0 个答案:

没有答案