【问题标题】:Updating ArrayAdapter issues更新 ArrayAdapter 问题
【发布时间】:2013-01-24 11:11:28
【问题描述】:

我有一个自定义 ArrayAdapter 的奇怪情况。 当我尝试使用新数据更新 adpater 时,新数据不会被更新,而是插入到列表视图的开头,并且一旦滚动列表视图,旧数据就会保留并可见。

更新

问题似乎是由片段包中的 ArrayList 引起的。 如果我没有在片段包的 onCreateView 中设置列​​表视图,我的更新代码可以正常工作,但现在我很困惑为什么会这样:

ArrayList<Collection> cityStoresList = fragmentBundle.getParcelableArrayList("stores");     
mStoresList.addAll(cityStoresList);

是否导致项目始终保留在列表中?

更新结束

以下是部分代码:(集合是自定义对象模型类)

ArrayList<Collection> mStoresList = new ArrayList<Collection>();

/** List Adapter */
private StoresListAdapter mListAdapter;

public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    boolean attach = false;
    if (container == null) {
        attach = true;
    }

    Bundle fragmentBundle = getArguments();
    ArrayList<Collection> cityStoresList = fragmentBundle.getParcelableArrayList("stores");     
    mStoresList.addAll(cityStoresList);

//inflater code not added here, but is present

mListAdapter = new StoresListAdapter(getActivity(), mStoresList);
        mListView.setAdapter(mListAdapter);

return layout;
}

我的自定义适配器如下:

    public class StoresListAdapter extends ArrayAdapter<Collection> {

        public StoresListAdapter(Context c, ArrayList<Collection> array) {
            super(c, 0, array);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // View from recycle
            View row = convertView;

            // Handle inflation
            if (row == null) {
                LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(R.layout.row_store, null);
            }

            // Get the Store
            Collection store = getItem(position);
                    //rest of code follows

            return row;
       }
   }

现在,当我想更新我的适配器时,我使用以下内容:

public void updateAdapter(ArrayList<Collection> storesList, final int listIndex) {
    mStoresList.clear();    
    mStoresList.addAll(storesList);         
        mListAdapter.notifyDataSetChanged();
     }

这就产生了我提到的问题。新项目看起来很好,但以前的项目仍然可见并在新项目之后添加。 这就像在 ArrayList 中添加新项作为第一项,而不是仅仅替换旧项。

有什么想法、建议吗?

【问题讨论】:

  • addAll 添加,它不会删除任何东西...
  • 是的,但我会在添加新列表之前清除它。
  • 你从哪里得到storesList?

标签: android android-arrayadapter


【解决方案1】:

好的,终于找到问题了。

因为整个事情都在一个片段中,所以在我附加数组时实际上调用了 oncreateView,所以发生的情况是我的 updateAdapter 方法被调用,项目被添加并显示,在视图实际可见之前。

然后触发 oncreateView 方法,并将原始捆绑项目添加到 Arraylist....

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    相关资源
    最近更新 更多