- 刚开始接触开关样式的按钮是在IOS系统上面,它的切换以及滑动十分帅气,深入人心。
所谓的开关按钮,就是只有2个状态:on和off,下图就是系统IOS 7上开关按钮效果。
起初我在android上我只会使用CheckBox去满足对应的功能。后来,查看开发文档发现,android也有了自己的原生态开关控件,并且在4.0版本中又优化加入了新的类似控件–Switch控件,以及使用起来十分简单的ToggleButton,可是它们只是带有切换效果,而不带有滑动切换效果,并且Switch控件只支持高版本的系统,对于2.3就不支持。所以,要想看如何实现滑动切换的效果,必须了解这些控件的实现方式。下面,让我们查看下android开发文档,看看这些是如何实现使用的。
注意:本文中涉及到自定义控件 并自定义配置属性declare-styleable,
如果你对于自定义控件的自定义配置属性还不是很了解可以看:android 自定义控件 使用declare-styleable进行配置属性(源码角度)
查看查看开发文档:
CompoundButton
| 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。并且此处不允许使用动画。
下面让我们来看看如何实现这个效果把:
一.使用ToggleButton控件实现:
使用ToggleButton控件十分方便,你可以看作他为一个CheckBox,只用设置它的button、background等几个属性即可。
首先:res–创建drawable文件夹 – 创建switch_btn.xml资源文件–作以下配置
view source print ?

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容,请联系我们,一经查实,本站将立刻删除。
如需转载请保留出处:https://51itzy.com/kjqy/56784.html