歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android按鈕被點擊文字顏色變化效果

Android按鈕被點擊文字顏色變化效果

日期:2017/3/1 11:01:06   编辑:Linux編程

有的時候做應用需要點擊按鈕時文字顏色也跟著變,松開後又還原,目前發現兩種解決方案:第一用圖片,如果出現的地方比較多,那麼圖片的量就相當可觀;第二,也就是本文講到的。廢話少說,先貼圖片,再上代碼。

正常效果:


按下效果:


先在values目錄創建color.xml文件,在裡面加入以下自定義顏色(注意不是用color標簽)的代碼:

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <resources>
  3. <drawable name="red">#f00</drawable>
  4. <drawable name="green">#0f0</drawable>
  5. <drawable name="gray">#ccc</drawable>
  6. </resources>
然後在res下新建drawable目錄,裡面新建btn_bg.xml和btn_color.xml文件,代碼如下:

btn_bg.xml

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:Android="http://schemas.android.com/apk/res/android">
  3. <item android:state_window_focused="false" android:state_enabled="true"
  4. android:drawable="@drawable/btn_test_normal" />
  5. <item android:state_enabled="false" android:drawable="@drawable/btn_test_normal" />
  6. <item android:state_pressed="true" android:drawable="@drawable/btn_test_press" />
  7. <item android:state_focused="true" android:drawable="@drawable/btn_test_normal" />
  8. </selector>
btn_color.xml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">
  3. <item android:state_focused="false" android:state_enabled="true" android:state_pressed="false"
  4. android:color="@drawable/red" />
  5. <item android:state_enabled="false" android:color="@drawable/gray" />
  6. <item android:state_pressed="true" android:color="@drawable/green" />
  7. <item android:state_focused="true" android:color="@drawable/red" />
  8. </selector>
最後是測試用的布局文件:
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent"
  6. android:background="@android:color/white"
  7. >
  8. <Button
  9. android:layout_width="wrap_content"
  10. android:layout_height="wrap_content"
  11. android:text="按下文字會變效果"
  12. android:textColor="@drawable/btn_color"
  13. android:background="@drawable/btn_bg"
  14. />
  15. <Button
  16. android:layout_width="wrap_content"
  17. android:layout_height="wrap_content"
  18. android:text="按鈕被禁用"
  19. android:enabled="false"
  20. android:textColor="@drawable/btn_color"
  21. android:background="@drawable/btn_bg"
  22. />
  23. </LinearLayout>
OK,大功告成!
Copyright © Linux教程網 All Rights Reserved