2012-07-28 45 views
2

我有一個自定義列表,每個項目有大約20個項目和三行。 我用日誌來跟蹤getView方法是如何被調用Android:當創建活動時系統調用getView兩次

public View getView(int position, View convertView, ViewGroup parent) { 

    Log.e("getView", "at position " + position); 
    View view = convertView; 

    if (view == null) { 
     LayoutInflater inflater = ((Activity) context).getLayoutInflater(); 
     view = inflater.inflate(resourceId, parent, false); 
    } 
      // my code here 

} 

然後,列表項加載時,我收到此日誌

「getView」,「在位置0」; 「getView」,「在位置1」; 「getView」,「在位置2」; 「getView」,「在位置3」; 「getView」,「在位置0」; 「getView」,「在位置1」; 「getView」,「在位置2」; 「getView」,「在位置3」; 「getView」,「在位置4」; 「getView」,「在位置5」; ..............

誰能告訴我爲什麼getView方法在0到3之間調用兩次?

+0

我不知道,但對我來說也是一樣,我只是測試過。我也想知道。 – Dalmas 2012-07-28 18:45:47

+0

請發佈您的自定義適配器代碼,以告知確切的解決方案。 – moDev 2012-07-28 19:26:03

回答

1

誰能告訴我爲什麼getView方法在0到3之間調用兩次?

getView方法被調用了兩次,因爲ListView,因爲它的一部分是onMeasure方法,調用適配器的getView方法來獲取行的View,看看他們是多麼大。我想你有三個可見的行,所以ListView將爲前三個可見的孩子調用getView方法三次。

+0

準確地說,在屏幕上的所有項目都會調用getView兩次。這裏是日誌:http://www.mediafire.com/view/?x98x5fpbywcmt0q# – 2012-07-29 01:45:53

+0

@MrStone沒有必要再次發佈日誌,我告訴過你爲什麼。你可以通過查看ListView的源代碼或者使用一個簡單的被忽略的ListView來檢驗這三個第一次調用是從onMeasure方法發生的。使用這個'ListView'(https://gist.github.com/3196065)而不是普通的並檢查日誌 – Luksprog 2012-07-29 04:32:43