Android ListView的item背景色設定

來源:互聯網
上載者:User

標籤:android   listview item bg   

1.如何改變item的背景色和按下顏色

  listview預設情況下,item的背景色是黑色,在使用者點擊時是黃色的。如果需要修改為自訂的背景顏色,一般情況下有三種方法:

  1)設定listSelector

  2)在布局檔案中設定item的background

  3)在adapter的getview中設定

  這三種方法都能達到改變item預設的背景色和按下顏色,下面來分別講解,但是在這之前需要先寫好selector.xml檔案;

<?xml version="1.0" encoding="utf-8"?><selector  xmlns:android="http://schemas.android.com/apk/res/android">    <item android:state_pressed="true" android:drawable="@color/light_blue"></item>    <item android:state_pressed="false" android:drawable="@color/sgray"></item></selector>

  在改變button或者listview的item預設背景色,就可以用到selector。drawable可以設定為色彩資源,也可以設定為圖片資源。

  1)設定listview的listSelector

<ListView   android:id="@+id/history_list"   android:layout_width="fill_parent"   android:layout_height="wrap_content"   android:divider="#565C5D"   android:dividerHeight="3dp"   android:listSelector="@drawable/selector"   android:cacheColorHint="@android:color/transparent"></ListView>

  2)在listitem的布局檔案中設定background屬性,下面是listitem的布局檔案

<?xml version="1.0" encoding="utf-8"?><RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"  android:layout_width="fill_parent"  android:layout_height="fill_parent"  android:background="@drawable/selector">    <TextView          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="記錄"          android:textColor="#ffffff"          android:textSize="20sp"          android:layout_centerInParent="true">     </TextView></RelativeLayout>

  3)在adapter的getView方法中設定

 if(convertView ==null) {     convertView = LayoutInflater.from(context).inflate(R.layout.listitem, null); } convertView.setBackgroundResource(R.drawable.selector);

  上述方法都能達到同樣的效果,就是改變item預設的背景色和點擊時的背景顏色,第三種方法最靈活,如果listview的奇數行和偶數行需要設定為不同的selector,只能用第三種方法。

Android ListView的item背景色設定

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.