剛開始接觸開關樣式的按鈕是在IOS系統上面,它的切換和滑動10分帥氣,深入人心。
所謂的開關按鈕,就是只有2個狀態:on和off,下圖就是系統IOS 7上開關按鈕效果。
起初我在android上我只會使用CheckBox去滿足對應的功能。后來,查看開發文檔發現,android也有了自己的原生態開關控件,并且在4.0版本中又優化加入了新的類似控件--Switch控件,和使用起來10分簡單的ToggleButton,可是它們只是帶有切換效果,而不帶有滑動切換效果,并且Switch控件只支持高版本的系統,對2.3就不支持。所以,要想看如何實現滑動切換的效果,必須了解這些控件的實現方式。下面,讓我們查看下android開發文檔,看看這些是如何實現使用的。
注意:本文中觸及到自定義控件 并自定義配置屬性declare-styleable,
如果你對自定義控件的自定義配置屬性還不是很了解可以看:android 自定義控件 使用declare-styleable進行配置屬性(源碼角度)
查看查看開發文檔:
CompoundButton
extends Button
implements Checkable
java.lang.Object |
||||
? |
android.view.View |
|||
|
? |
android.widget.TextView |
||
|
|
? |
android.widget.Button |
|
|
|
|
? |
android.widget.CompoundButton |
Known Direct Subclasses CheckBox,RadioButton,Switch,ToggleButton |
以上4類都是開關類型切換的控件,它們的父類都是CompoundButton。
它對應的方法和類有:
點擊選擇監聽接口。
Nested Classes |
||
interface |
CompoundButton.OnCheckedChangeListener |
Interface definition for a callback to be invoked when the checked state of a compound button changed. |
返回左右填充的VIEW,加上間隔
Public Methods |
|
int |
getCompoundPaddingLeft()Returns the left padding of the view, plus space for the left Drawable if any. |
int |
getCompoundPaddingRight()Returns the right padding of the view, plus space for the right Drawable if any. |
boolean:是不是被選中。
boolean |
isChecked() |
設置Button的Drawable屬性
void |
setButtonDrawable(int resid)Set the background to a given Drawable, identified by its resource id. |
設置是不是選中
void |
setChecked(boolean checked)Changes the checked state of this button. |
改變當前的狀態,true-->false ;false-->true
void |
toggle()Change the checked state of the view to the inverse of its current state |
控件全局 繪制
void |
onDraw(Canvas canvas)Implement this to do your drawing. |
protected void onDraw (Canvas canvas)
實現你自己的繪制。
參數
canvas 在畫布上繪制背景
protected boolean verifyDrawable (Drawable who)
如果你的視圖子類顯示他自己的可視化對象,他將要重寫此方法并且為了顯示可繪制返回true。此操作允許進行繪制時有動畫效果。
確認當重寫從方法時,需調用父類相應方法。
參數
who 需判斷的可繪制對象(Drawable)。如果是你要顯示的對象,返回True,否則返回調用父類的結果。
返回值
boolean 如果可繪制對象(Drawable)已在視圖中顯示,返回True否則返回false。并且此處不允許使用動畫。
下面讓我們來看看如何實現這個效果把:
1.使用ToggleButton控件實現:
使用ToggleButton控件10分方便,你可以看做他為1個CheckBox,只用設置它的button、background等幾個屬性便可。
首先:res--創建drawable文件夾 -- 創建switch_btn.xml資源文件--作以下配置