【问题标题】:Android: ListView background for each row-itemAndroid:每个行项的 ListView 背景
【发布时间】:2012-01-12 09:09:36
【问题描述】:

我有以下列表视图:

<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。 提前致谢!

【问题讨论】:

  • 为列表行创建 xml 文件并在 listview 适配器类中扩展该 xml 文件
  • 你不能直接从 xml 文件中给每一行不同的颜色...你必须为你的行创建 xml 并在填充你的行 xml 时为行的背景颜色编写条件

标签: android list listview


【解决方案1】:

您需要为您的行指定一个服装视图布局,例如 LinearLayout 左右。 在此布局中,您可以指定背景颜色或图像或其他任何内容。

稍后在 getView() 函数中的列表适配器中,您可以使用加载此布局 布局膨胀并返回此视图。

【讨论】:

    【解决方案2】:
    *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));* 
    

    【讨论】:

      猜你喜欢
      • 2011-05-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-20
      相关资源
      最近更新 更多