Android使用selector自訂按鈕

來源:互聯網
上載者:User

標籤:android   按鈕   ui   自訂   selector   

可視化編輯器,alt+1到9鍵,切換到工具區,tab鍵,選擇按鈕,esc鍵,返回編輯
Android使用selector自訂按鈕

       以前定義按鈕的時候,想使用自訂的Button總是習慣在activity中擷取該按鈕然後,重寫該按鈕的onTouchListener然後在當中切換按鈕的背景圖片。這樣做不但使activity中的代碼變得臃腫而且不能該按鈕不能達到重用的目的。



       後來接觸到了Android 中的selector挺好用的,下面詳細講解一下如何使用selector,首先在res\drawable檔案夾下建立一個xml檔案

       650) this.width=650;" src="http://img.blog.csdn.net/20141020204242187?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvdTAxMTc4MjUyOA==/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/Center" />

     再在drawable檔案中添加你想應用在按鈕上的圖片,包括按下的圖片和不按時的圖片。

     然後在該檔案中添加:drawable

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android" >     <!--當按鈕獲得焦點時定義顯示的圖片-->     <item                   android:state_focused = "true"                   android:drawable = "@drawable/image_btn_down"/>        <!--當按鈕被選中時定義現實的圖片 -->        <item                   android:state_selected = "true"                   android:drawable = "@drawable/image_btn_down"/>    <!--當按鈕被點擊時定義顯示的圖片-->            <item                   android:state_pressed = "true"                   android:drawable = "@drawable/image_btn_down"/>     <!--預設按鈕沒有被選中時顯示的圖片-->               <item android:drawable = "@drawable/image_btn_up" />   </selector>

 

       該檔案名稱字叫做button_selector.xml,完成之後,把你想應用的按鈕的drawable屬性改為@drawable/button_selector就可以了 如下:

<Button                        android:id="@+id/button_add"                        android:layout_width="115dp"                        android:layout_height="wrap_content"                        android:layout_margin="5px"                        android:layout_weight="1"                        android:background="@drawable/button_selector"                        android:text="自訂按鈕" />






  開發微博推薦:   http://crh.chinacloudsites.cn/



本文出自 “開發人員” 部落格,請務必保留此出處http://tang1513.blog.51cto.com/7678175/1566330

Android使用selector自訂按鈕

聯繫我們

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