簡體   English   中英

在Android中更改自定義Listview項目背景顏色

[英]Change Custom Listview Item Background Color in Android

我想更改Custom Listview的每個項目背景顏色。 因此,使用適配器時,我使用了getView()但是它不起作用。 這個怎么做 ?

我的代碼如下:

adapter = new SimpleAdapter(this, aaReportData, R.layout.report_card1, new String[] { "Topic" }, new int[] { R.id.tvTopic}) {

                @Override
                public View getView(int position, View convertView,
                        ViewGroup parent) {
                    // TODO Auto-generated method stub
                    convertView.setBackgroundColor(R.color.lightish);
                    return convertView;
                }
            };

正如@Dhaval所說,我為父級布局定義了背景色,並且效果很好。 現在,我希望每個列表項之間都有一些空間,因此我使用了Drawable並將顏色和邊框底部設置為白色以保留一些空間。

現在工作正常,並且按我的要求得到了結果。 非常感謝大家。

您應該使用setBackgroundResource()方法而不是setBackgroundColor()

試用以下代碼

view.setBackgroundResource(R.color.blue)
adapter = new SimpleAdapter(this, aaReportData, R.layout.report_card1, new String[] { "Topic" }, new int[] { R.id.tvTopic}) {

            @Override
            public View getView(int position, View convertView,
                    ViewGroup parent) {
                View v = super.getView(position, convertView, parent);
                // TODO Auto-generated method stub
                v.setBackgroundResource(R.color.lightish);
                return convertView;
            }
        };
convertView = View.inflate(mContext, R.layout.list_item, null);
convertView.setBackgroundColor(mContext.getResources().getColor(R.color.lightish));

您應該在上方的行中充氣列表項視圖,以設置顏色以使用。

ListView使用此選擇器xml

<item>
<shape android:shape="rectangle">
   <gradient
       android:startColor="@android:color/holo_orange_light"
       android:endColor="@android:color/holo_red_light"
       android:angle="270"/>
   </shape>
</item>

更新:

在您的ListView更改,例如:

    <ListView
    android:id="@+id/listView_contact"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="@android:color/darker_gray"
    android:dividerHeight="0.3dp"
    android:background="@android:color/transparent"
    android:listSelector="@drawable/productlistselector">
</ListView>

您可以使用divider並將其背景設置為transparent而不用設計新的自定義背景。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM