Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android ListView item 背景色與按下色的三種設置方式

編輯:關於 Android 程式設計

ListView 默認情況下 item 背景是黑色,點擊時變成黃色。想換成自定義配色,一般有三種做法。動手之前,先準備好 selector:

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

selector 不只可以用在 Button 或 ListView item 上,任何有狀態的 View 都適用。drawable 既可以指向顏色資源,也可以指向圖片資源。建議再補上 android:state_focused="true" 與 android:state_selected="true",以兼顧非觸控設備的焦點導航。

方法一:設置 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" />

listSelector 控制的是「被按下 / 選中時」的樣子,item 本身的常態背景仍由 item 布局決定。

這裡的 android:cacheColorHint="@android:color/transparent" 非常重要。ListView 為了效能會對 item 做位圖快取,若你的 item 有非透明背景,不設置這個屬性,滑動時會出現背景色閃爍或錯亂。它可以理解為告訴系統「我的背景是不透明的,別再幫我疊那層半透明遮罩」。

方法二:在 item 布局中設置 background

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    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" />
</RelativeLayout>

這種寫法直觀,且 selector 的 state_pressed 能正常跟隨 item 的按壓狀態,適合所有 item 樣式一致的場景。

方法三:在 Adapter 的 getView 中設置

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    if (convertView == null) {
        convertView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.listitem, parent, false);
    }
    convertView.setBackgroundResource(R.drawable.selector);
    return convertView;
}

三種方法都能達到同樣效果,但第三種最靈活。如果需要奇數行與偶數行使用不同背景(常見的斑馬紋效果),就只能靠它:

convertView.setBackgroundResource(position % 2 == 0
        ? R.drawable.selector_even
        : R.drawable.selector_odd);

還需要注意的幾件事

  • selector 的順序有意義。後寫的會覆蓋前面的,特例請放在前面,兜底項放最後。
  • color 與 drawable 要分清。selector 根節點用 item 的 android:drawable 屬性;若寫成 android:color 而引用的是圖片,會在執行期報資源類型不匹配。
  • item 高度別用 match_parent。範例改成 wrap_content 才符合直覺。
  • Recycler 場景同理。遷移到 RecyclerView 後,按下效果需要自己在 item 上處理(例如用 RippleDrawable 或背景 selector 加 setPressed),因為 RecyclerView 不再提供 listSelector。
  • Android 5.0 起推薦 RippleDrawable。用 <ripple> 包一層 color,能獲得符合 Material Design 的水波紋反饋,比單純換色更自然。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved