2012-01-12 40 views
0

我有以下的ListView:安卓:ListView控件背景的每一行項目

<ListView android:id="@android:id/list" android:layout_width="fill_parent" android:divider="@drawable/line" 
     android:layout_height="fill_parent" android:background="@drawable/bg"/> 

但我要爲每個行項目的背景。當我設置android:background屬性時,我改變了整個列表的背景,而不僅僅是每一行。

如何設置行中每個項目的可繪製背景?我已經嘗試了一切。我唯一可以改變的是在行之間顯示的android:divider drawable。 在此先感謝!

+0

創建一個列表行xml文件和該充氣XML文件中你的ListView適配器類 – 2012-01-12 09:18:43

+0

你不能直接給每一行從XML文件不同的顏色......你必須爲你的行來創建XML和寫入條件行的背景顏色,同時膨脹你的行xml – Maverick 2012-01-12 09:34:13

回答

0

你需要爲你的行指定一個costum視圖佈局,就像一個LinearLayout左右那樣。 在這種佈局中,您可以指定背景顏色或圖像或以前的任何內容。

後來在你的列表中的適配器在getView()函數中,你用這個佈局加載 佈局inflater並返回這個視圖。

0
*Use Custom Adapter. 

First create Custom Adapter class and set this to fill listView 

ex: 

class CusAdapter extends BaseAdapter 
{ 

    private Context mContext; 

    public ImageAdapter(Context c) 
    { 

    mContext = c; 

    } 

    public int getCount() 

    { 

    return 10; 
    } 

    public Object getItem(int position) 

    { 

    return null; 

    } 

    public long getItemId(int position) 
    { 

    return 0; 

    } 

    // create a new ImageView for each item referenced by the Adapter 

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

      //create a layout for listView 

      LinearLayout lLayout = new LinearLayout(this); 

     lLayout.setOrientation(LinearLayout.VERTICAL); 

     lLayout.setLayoutParams(new LayoutParams(
      LayoutParams.MATCH_PARENT, 

     LayoutParams.MATCH_PARENT)); 


     //check position and set background 

      if(position%2==0) 
      { 

        lLayout.setBackgroundResource(R.id.bckResource1); 

       } 
      else 

        lLayout.setBackgroundResource(R.id.bckResource2); 

     return lLayout; 

    } 

} 

after this set this adapter to fill listview 

listView.setAdpater(new cusAdapter(this));*