2011-06-08 47 views

回答

2
  1. 用於小區創建一個佈局XML
  2. 對於行
  3. 創建一個佈局XML在其中定義行(頭)和低於 3.A. ListView中創建一個佈局XML或者,您可以使用ListView的addHeaderView(View v)方法
  4. 創建自定義適配器並覆蓋getView方法。檢查每隔一行(位置%2 == 0)並更改行的顏色

我做了一個示例項目,可以從here下載它。

1)創建一個單元的佈局XML

RES /佈局/ cell.xml

<?xml version="1.0" encoding="utf-8"?> 
<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="0dp" 
    android:layout_height="match_parent" 
    android:layout_weight="1" 
    android:paddingTop="10dp" 
    android:paddingBottom="10dp" 
    android:paddingLeft="4dp" 
    android:background="@drawable/item_light_bg" 
    /> 

如果你希望你的行是相同的寬度指定layout_width = 「0dp」 和layout_weight = 「1」。

2.),用於一個行創建一個佈局XML

RES /佈局/ list_item.xml

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content"> 
<include 
    android:id="@+id/firstCol" 
    layout="@layout/cell" 
    /> 
<include 
    android:id="@+id/secondCol" 
    layout="@layout/cell" 
    /> 
<include 
    android:id="@+id/thirdCol" 
    layout="@layout/cell" 
    /> 
<include 
    android:id="@+id/fourthCol" 
    layout="@layout/cell" 
    /> 
<include 
    android:id="@+id/fifthCol" 
    layout="@layout/cell" 
    /> 
</LinearLayout> 

3.)創建一個佈局XML在其中定義行(頭)和這

RES /佈局/ main.xml中

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
> 
<include 
     android:id="@+id/header" 
     layout="@layout/list_item" 
    /> 
<ListView 
     android:id="@android:id/list" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
    /> 
</LinearLayout> 

4)下面的ListView控件創建自定義適配器和奧雅納使用getView方法。檢查是否爲每隔一行(位置%2 == 0),並更改行的顏色

public class MyAdapter extends SimpleAdapter { 
    ... 
    @Override 
    public View getView(int position, View convertView, ViewGroup parent) { 
     LinearLayout v = (LinearLayout)super.getView(position, convertView, parent); 
     if (position % 2 == 0) 
      v.setBackgroundColor(Color.rgb(0, 0, 55)); 
     else 
      v.setBackgroundColor(Color.rgb(22, 22, 88)); 
     return v; 
    } 
    ... 

此外,您可能需要您的ListView是靜態的(例如,不可點擊和選擇)。爲此,請覆蓋適配器中的isEnabled方法。

@Override 
public boolean isEnabled(int position) { 
    return false; 
} 
+0

這是我想要的東西,非常感謝你對此的解釋和代碼 – 2011-06-09 05:38:27

+0

示例項目鏈接是死的(http://dl.dropbox.com/u/296580/Test.zip) – 2015-04-15 05:30:10