標籤:android style blog http color io ar 檔案 sp
有的時候做應用需要點擊按鈕時文字顏色也跟著變,鬆開後又還原,目前發現兩種解決方案:第一用圖片,如果出現的地方比較多,那麼圖片的量就相當可觀;第二,也就是本文講到的。廢話少說,先貼圖片,再上代碼。
正常效果:
按下效果:
先在values目錄建立color.xml檔案,在裡面加入以下自訂色彩(注意不是用color標籤)的代碼:
<?xml version="1.0" encoding="utf-8"?><resources> <drawable name="red">#f00</drawable> <drawable name="green">#0f0</drawable> <drawable name="gray">#ccc</drawable></resources>
然後在res下建立drawable目錄,裡面建立btn_bg.xml和btn_color.xml檔案,代碼如下:
btn_bg.xml
<?xml version="1.0" encoding="utf-8"?><selector xmlns:android="http://schemas.android.com/apk/res/android"> <item android:state_window_focused="false" android:state_enabled="true" android:drawable="@drawable/btn_test_normal" /> <item android:state_enabled="false" android:drawable="@drawable/btn_test_normal" /> <item android:state_pressed="true" android:drawable="@drawable/btn_test_press" /> <item android:state_focused="true" android:drawable="@drawable/btn_test_normal" /></selector>
btn_color.xml
<?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="@drawable/red" /> <item android:state_enabled="false" android:color="@drawable/gray" /> <item android:state_pressed="true" android:color="@drawable/green" /> <item android:state_focused="true" android:color="@drawable/red" /></selector>
最後是測試用的布局檔案:
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:background="@android:color/white" > <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按下文字會變效果" android:textColor="@drawable/btn_color" android:background="@drawable/btn_bg" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="按鈕被禁用" android:enabled="false" android:textColor="@drawable/btn_color" android:background="@drawable/btn_bg" /> </LinearLayout>
OK,大功告成!
原文:http://blog.csdn.net/maylian7700/article/details/6978131
android按鈕被點擊文字顏色變化效果