2010-08-05 45 views
13

我在我的ListActivity上有ListView,我希望ListView的行成爲3種不同佈局中的一種。我的列表中的第一個項目總是使用佈局A,我的列表中的第二個項目總是使用佈局B,並且所有後續項目都將使用佈局C.帶有多個項目佈局的ListViews

這裏是我的getView函數:

@Override 
public View getView(int position, View convertView, ViewGroup parent) { 
    // get the View for this list item 
    View v = convertView; 
    if (v == null) { 
     LayoutInflater vi = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     switch (position) { 
      case 0: 
       v = vi.inflate(R.layout.layout_A, parent, false); 
       break; 
      case 1: 
       v = vi.inflate(R.layout.layout_B, parent, false); 
       break; 
      default: 
       v = vi.inflate(R.layout.layout_C, parent, false); 
       break; 
     } 
    } 
    switch (position) { 
     case 0: 
      TextView txtLabel1 = (TextView)findViewById(R.id.label1); 
      TextView txtLabel2 = (TextView)findViewById(R.id.label2); 
      if (txtLabel1 != null) { 
       txtLabel1.setText("sdfasd"); 
      } 
      if (txtLabel2 != null) { 
       txtLabel2.setText("dasgfadsasd"); 
      } 
      break; 
     default: 
      break; 
    } 
    // return the created view 
    return v; 
} 

R.id.label1R.id.label2TextViewsR.layout.layout_A。但是,嘗試設置它們後,txtLabel1txtLabel2爲空。爲什麼?

我在調試器中跳過了這段代碼,它膨脹了正確的佈局(R.layout.layout_A),並陷入下面的正確情況,設置了R.id.label1R.id.label2文本。

另外,如果有更好的方法來做到這一點,請讓我知道。

+0

檢查[本教程](http://android.amberfog.com/?p=296)。他們解釋了與你想要達到的目標類似的東西。 – Macarse 2010-08-05 15:46:02

回答

4

看起來像「查看v = convertView;如果(v == null){...」是一個問題。您應該每次重新創建視圖,因爲您不知道給定視圖的類型。此外,您可以使用視圖方法來更有效地實現。你可以在這個博客中找到一些想法:http://codinglines.frankiv.me/post/18486197303/android-multiple-layouts-in-dynamically-loading

+0

這是一個非常糟糕的主意,並會顯着減慢性能。 Macarse會給出一個很好的例子,試圖重複使用這些視圖。 – Chris 2013-08-27 16:55:37