Android學習筆記之ImageButton

來源:互聯網
上載者:User

顯示一個可以被使用者點擊的圖片按鈕,預設情況下,ImageButton看起來像一個普通的按鈕,在不同狀態(如按下)下改變背景顏色。按鈕的圖片可用通過<ImageButton>
XML元素的android:src屬性或setImageResource(int)方法指定。

 

為了表示不同的按鈕狀態(焦點,選擇等),你可以為各種狀態定義不同的圖片。例如,定義藍色圖片為預設圖片,黃色圖片為擷取時焦點時顯示的圖片,黃色圖片為按鈕被按下時顯示的圖片。一個簡單的方法可以做到這點——通過XML的"selector."配置,如下:

儲存上面的XML到res/drawable/檔案夾下(註:注意檔案名稱大小寫!),將該檔案名稱作為一個參數設定到ImageButton的
android:src屬性(註:如xml檔案名稱為myselector.xml,那麼這裡設定為"@drawable/myselector",設定android:background也是可以的,但效果不太一樣)。Android根據按鈕的狀態改變會自動的去XML中尋找相應的圖片以顯示。

<item>元素的順序很重要,因為是根據這個順序判斷是否適用於當前按鈕狀態,這也是為什麼正常(預設)狀態指定的圖片放在最後,是因為它只會在pressed和focused都判斷失敗之後才會被採用。(註:例如按鈕被按下時是同時獲得焦點的,但是獲得焦點並不一定按了按鈕,所以這裡會按順序尋找,找到合適的就不往下找了。這裡按鈕被點擊了,那麼第一個將被選中,且不再在後面尋找其他狀態。)

 

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="ImageButton"/>    <ImageButton        android:id="@+id/image1"        android:layout_width= "wrap_content"        android:layout_height="wrap_content"        android:src= "@drawable/macos01"/></LinearLayout>

 

點擊後

聯繫我們

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