2013-03-14 98 views
0

在我的應用程序中,我有一個帶有「部分」的ListView。對於每個項目,我都添加了一個字母,但僅對於以該字母開頭的第一個字詞纔可見。它工作正常,但如果我在我的ListView中向下滾動,訂單更改,這意味着該信件將轉到下一個項目。ListView刷新GetView()

例子:

A 
-- 

- Alligator 
- Ant 
- Antelope 
- Ape 

但是,當我向下滾動,會發生以下情況:

- Aligator 

A 
-- 
- Ant 
- Antelope 
- Ape 

功能,增加了我在GetView()

我該如何解決實施信這個問題? 我讀過ListView在滾動時刷新,我該如何禁用刷新?還是有另一種方法來解決這個問題?

protected string old_char = ""; 
     public override View GetView(int position, View convertView, ViewGroup parent) 
     { 
       var item = sw_items [position]; 
       View view; 

      convertView = null; 

       view = (convertView ?? 
        this.context.LayoutInflater.Inflate (Resource.Layout.ItemLayout, 
        parent, 
        false)) as LinearLayout; 

       var txtTitle = view.FindViewById<TextView> (Resource.Id.txtTitle); 
       txtTitle.SetText (sw_items [position].name, TextView.BufferType.Normal); 

       var alfabet = view.FindViewById<TextView> (Resource.Id.alfabet); 
       var linAlfabet = view.FindViewById<LinearLayout> (Resource.Id.Lin_Alfabet); 

      if (convertView == null) { 
      string cnv_char = item.name [0].ToString().ToUpper(); 
      alfabet.Text = cnv_char; 
      if (cnv_char != old_char) { 
       alfabet.Visibility = ViewStates.Visible; 
       linAlfabet.Visibility = ViewStates.Visible; 
      } else { 
       alfabet.Visibility = ViewStates.Gone; 
       linAlfabet.Visibility = ViewStates.Gone; 
      } 

      //saving previous char 
      old_char = cnv_char; 
      } 

       return view; 


     } 

     } 

我在做什麼錯?

+2

添加您在適配器上使用的代碼。 – madlymad 2013-03-14 09:33:10

回答

1

修訂

首先,用於getView()實現基本方案如下。

if (convertView == null) { 
    // the system does not want me to recycle a view object, so create a new one 
    LayoutInflater inflater = (LayyoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
    convertView = inflater.inflate(R.layout.your_layout_file, parent, false); 
} 
// here, set up the convertView object, no matter whether it was recycled or not 
... 
return convertView; 

由於代碼片斷您發佈,所有你可能需要做的是:1。去除convertVire = null;聲明,雅鼎建議和2.去除環境if (convertView == null) {包括關閉}圍繞string cnv_char... old_char = cnv_char塊。請務必正確設置convertView,因爲它不保證是新鮮的對象。

第二個,您的代碼依賴getView()被調用的特定順序,情況並非如此。目前,您正在依靠old_char設置爲最後一個項目的起始字母(按它們在列表中的顯示順序)。這不是保證。

我建議您使用position參數來訪問列表的前一個條目(當然除外),並檢查是否有差異,如果沒有前導或顯示當前項目的起始字母以不同的字母開頭。

+0

不幸的是,我不知道如何實現這個我的代碼。 – lukso 2013-03-14 10:41:27

+0

@lukso你可以描述一下你試圖遵循這個方案時遇到的問題。 – 2013-03-14 10:44:28

+0

我正在使用C#並且發佈的是Java。這就是爲什麼我不能實現這一點。 – lukso 2013-03-14 11:02:39

0

的ListView重用堆棧意見,以取代被向上滾動至底部

嘗試作爲之前添加以下語句中的代碼再次把它的觀點: -

convertView = NULL;

之前它檢查

如果(convertView == NULL);

+0

將它添加到您的customListAdapter的getView()方法中。 – 2013-03-14 09:31:18

+1

值得注意的是,這種建議的方法 - 忽略視圖的回收 - 絕對不是Android對getView()實現的期望,它也不會節省應用程序的任何努力 - 如何設置現有的對象比創建一個新創建的對象效率低?此外,如果原始海報發生了特定的執行錯誤,您的解決方案只會解決問題,這是不能保證的。如果你先問他,如果你指出你的解決方案不是Android-ish,那本來是很好的。 – 2013-03-14 10:07:13