本文實(shí)例講述了Android開發(fā)實(shí)現(xiàn)按鈕點(diǎn)擊切換背景并修改文字顏色的方法。分享給大家供大家參考,具體如下:
其實(shí)原理很簡單,用到的是selector,用來設(shè)置android:background和android:textcolor屬性,selector可以用來設(shè)置默認(rèn)時(shí)候、點(diǎn)擊時(shí)候的背景圖片和文字顏色的屬性,過程如下:
這兩個(gè)文件如下:
1.當(dāng)點(diǎn)擊按鈕,改變文字的顏色:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_focused="false" android:state_enabled="true" android:state_pressed="false" android:color="#000000" /> <item android:state_enabled="false" android:color="#000000" /> <item android:state_pressed="true" android:color="#ffffff" /> <item android:state_focused="true" android:color="#000000" /></selector>
2.當(dāng)點(diǎn)擊按鈕,改變按鈕的背景:
<?xml version="1.0" encoding="utf-8"?><selector xmlns:Android="http://schemas.android.com/apk/res/android"> <!-- 定義按鈕按下時(shí)的圖片 --> <item Android:drawable="@drawable/blue" Android:state_pressed="true"/> <!-- 定義按鈕默認(rèn)的圖片 --> <item Android:drawable="@drawable/gray"/></selector>
是不是很簡單,不用再用java代碼來進(jìn)行設(shè)置,只需要設(shè)置到你所需要的Textview或者button,如下使用方式:
<TextView android:id="@+id/menu_logout" android:layout_width="fill_parent" android:layout_height="fill_parent" android:layout_weight="1" android:background="@drawable/btnselector" android:drawableLeft="@drawable/menu_logout" android:drawablePadding="10dp" android:gravity="center_vertical" android:text="@string/logout" android:textColor="@drawable/btnselectorcolor" android:textSize="@dimen/Menu_Font_Size" />
成功完成?。。?!希望本文所述對大家Android程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注