2012-01-12 64 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));*