Android 中的ListView選中項的背景顏色怎麼設定?

來源:互聯網
上載者:User

 

android中ListView獲得焦點的項預設是黃色的(模擬器上) 現在因為需求想要自己定義被選中項的背景能實現嗎?

最佳答案

        完全可以實現,這用到了Android的Selector(根據組件的狀態顯示該狀態對應的圖片,並以此圖片作為背景顯示)。 把下面的XML檔案儲存成你自己命名的.xml檔案(比如list_bg.xml),注意,這個檔案相當於一個背景圖片選取器,在系統使用時根據ListView中的清單項目的狀態來使用相應的背景圖片,什麼情況使用什麼圖片我在下面都進行了說明。還有,你可以把它看成是一個圖片來使用,放於drawable目錄下,配置背景屬性android:background="@drawable/list_bg"就能達到你需要的目的了。

<?xml version="1.0" encoding="utf-8" ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_window_focused="false" android:drawable="@drawable/沒有焦點時圖片背景" />
    <item android:state_focused="true" android:state_pressed="true"     <!--雙條件-->
        android:drawable="@drawable/非觸摸模式下獲得焦點並單擊時的背景圖片" />
    <item android:state_focused="false" android:state_pressed="true"
        android:drawable="@drawable/觸摸模式下單擊時的背景圖片" />
    <item android:state_selected="true" android:drawable="@drawable/選中時的圖片背景" />
    <item android:state_focused="true" android:drawable="@drawable/獲得焦點時的圖片背景" />
    <item android:drawable="@drawable/silver" /> <!--default color -->
</selector>

 ---------------------------------------------------------------------------------------------------------------

在values下建立一個color.xml<?xml version="1.0" encoding="utf-8"?>
<resources>
    <drawable name="darkgray">#808080FF</drawable>
    <drawable name="white">#FFFFFFFF</drawable>
    <drawable name="silver">#00ffffff</drawable>   <!-- 透明色 -->
</resources>

-------------------------------------------------------------------------------------------------------------------------------------------------

main布局檔案中的系統 ListView 控制項,注意這不是 ListViewItem 控制項。

<ListView android:id="@id/android:list" android:layout_width="fill_parent"
          android:layout_height="400dip" android:drawSelectorOnTop="false" 

          android:listSelector="@drawable/list_selector_color"/>
<TextView android:id="@id/android:empty"
         android:layout_width="wrap_content" android:layout_height="wrap_content"
          android:text="Can not find the file!" />

 -------------------------------------------------------------------------------------------------------------------

你可以看下原始碼ListView清單項目背景的預設實現 :

SDK目錄\platforms\android-xx\data\res\drawable\list_selector_background.xml

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.