天天看點

Android listview下拉重新整理,出現重複資料

在開發中,涉及到ListView的重新整理,一般分為兩種情況,一種是listview形式的,一種是 在代碼中建立自定義布局,采用addView形式的

重新整理的時候,如果沒有清楚緩存(清空view)的話,會出現每次重新整理都會重新加載資料,并且之前的舊資料不清空.這樣就導緻了資料的重複

解決辦法很簡單.

假如你是用的擴充卡,那麼就在你網絡請求回調回來之後,判斷list或者請求的對象是否為空,不為空的話 先adapter.clear(),然後再使用adapter.add(view)或者adapter.addAll(list)

假如你是在代碼中自定義listview布局的話, 那麼在每次請求資料回來之後 ,先layout.removeAllViews();

通過上面兩種方式,就可以避免資料的重複!

上一段第二種的代碼

<LinearLayout

    android:id="@+id/lv_content"

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:layout_below="@+id/divider_bottom"

    android:orientation="vertical"></LinearLayout>

這個是xml布局中裝載listView的布局

清除的時候就這樣寫

lv_content.removeAllViews();

然後再把請求回來的資料加進來

RelativeLayout  layout_content = (RelativeLayout) LayoutInflater.from(getActivity()).inflate(R.layout.mine_list_item_notjump, null);

                            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, DensityUtil.dip2px(48));

                            layout_content.setLayoutParams(params);

lv_content.addView(layout_content )括号中的view是listview item的布局

這樣就ok了