2013-01-24 46 views
0

我有一個奇怪的情況與自定義ArrayAdapter。 當我嘗試用新數據更新adpater而不是正在更新的數據時,新數據將插入到listview的開頭,並且一旦滾動listview,舊數據就會保留並可見。更新ArrayAdapter問題

UPDATE

看來這個問題是由從片段包中的ArrayList引起的。 如果我不從片段包設置列表視圖中onCreateView,我更新的代碼工作正常,但現在我困惑,爲什麼這樣的:

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

導致該項目始終保持在名單上? UPDATE OF

END

下面是部分代碼:(Collection是一個自定義對象模型類)

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中的新項目作爲第一項,而不是隻替換舊項目。

任何想法,建議?

+0

中的addAll補充說,它不會刪除任何東西...... – njzk2

+0

是的,但在此之前,我將其清除添加新的列表。 – Lefteris

+0

你從哪裏得到storesList? – njzk2

回答

0

好的,終於找到了問題。

因爲整件事都在一個片段內,所以oncreateView實際上是在我附加數組時調用的,所以會發生什麼是我的updateAdapter方法被調用,項目被添加並顯示在視圖實際可見之前。

然後oncreateView方法被觸發,原件捆的項目被添加到ArrayList ....