Android中實現類似iOS的SwitchButton控制元件

yangxi_001發表於2014-10-09
iOS的SwitchButton深入人心,也被Android上的產品設計借鑑,在Android4.0中,系統就帶有原生的Switch控制元件了。但是在老版本的Android上,怎樣實現這個功能呢?
最簡單的方法就是,把SwitchButton看成是個CheckBox或者ToggleButton,直接設定button屬性或者background屬性就可以。
[html] view plaincopy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <selector xmlns:android="http://schemas.android.com/apk/res/android">  
  3. <item android:drawable="@drawable/check_box_on" android:state_checked="true"/>  
  4. <item android:drawable="@drawable/check_box_off" android:state_checked="false"/>  
  5. </selector>  

但是這樣實現,並沒有像iOS上那樣的滑動動畫效果。下面介紹兩種自定義的SwitchButton的控制元件的開源庫。
http://ankri.de/switch-button-for-android-2-3-gingerbread/ 
這篇博文中詳細介紹了其實現方法,也可以下載到原始碼。這個可以用手拖動開關,效果非常接近了。但是也是有缺點的,不能實現背景移動,其背景是一個ProgressDrawable。
https://github.com/Issacw0ng/SwitchButton
這個是我堅果的最完美模擬iOS效果的SwitchButton。可以實現拖動,背景也可以跟著拖動。但是程式碼的實現上不是那麼嚴謹,不能調整大小,不能靈活自定義樣式。

這兩個的實現原理基本類似,程式碼也比較少,有興趣的同學可以研究一下原始碼,非常值得學習的開源專案。

相關文章