SwitchButton 开关按钮 的多种实现方式 (附源码DEMO)

刚开始接触开关样式的按钮是在IOS系统上面,它的切换以及滑动十分帅气,深入人心。

所谓的开关按钮,就是只有2个状态:on和off,下图就是系统IOS 7上开关按钮效果。

起初我在android上我只会使用CheckBox去满足对应的功能。后来,查看开发文档发现,android也有了自己的原生态开关控件,并且在4.0版本中又优化加入了新的类似控件–Switch控件,以及使用起来十分简单的ToggleButton,可是它们只是带有切换效果,而不带有滑动切换效果,并且Switch控件只支持高版本的系统,对于2.3就不支持。所以,要想看如何实现滑动切换的效果,必须了解这些控件的实现方式。下面,让我们查看下android开发文档,看看这些是如何实现使用的。

注意:本文中涉及到自定义控件 并自定义配置属性declare-styleable,

如果你对于自定义控件的自定义配置属性还不是很了解可以看:android 自定义控件 使用declare-styleable进行配置属性(源码角度)

查看查看开发文档:

CompoundButton

extends Buttonimplements Checkable

java.lang.Object

android.view.View

android.widget.TextView

android.widget.Button

android.widget.CompoundButton

Known Direct Subclasses

以上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

()Returns the left padding of the view, plus space for the left Drawable if any.

int

()Returns the right padding of the view, plus space for the right Drawable if any.

boolean:是否被选中。

boolean

()

设置Button的Drawable属性

void

(int resid)Set the background to a given Drawable, identified by its resource id.

设置是否选中

void

(boolean checked)Changes the checked state of this button.

改变当前的状态,true–>false ;false–>true

void

()Change the checked state of the view to the inverse of its current state

控件全局绘制

void

canvas)Implement this to do your drawing.

protected void onDraw (Canvas canvas)

实现你自己的绘制。

参数

canvas 在画布上绘制背景

protected boolean verifyDrawable (Drawable who)

  确认当重写从方法时,需调用父类相应方法。

参数

返回值

下面让我们来看看如何实现这个效果把:

一.使用ToggleButton控件实现:

使用ToggleButton控件十分方便,你可以看作他为一个CheckBox,只用设置它的button、background等几个属性即可。

首先:res–创建drawable文件夹 — 创建switch_btn.xml资源文件–作以下配置

<?xml version="1.0" encoding="utf-8"?><selector xmlns:android=""><item android:state_checked="true" android:drawable="@drawable/ios7_switch_on" /><item android:drawable="@drawable/ios7_switch_off" /></selector>其中:android:state_checked="true" 表示选中on时候的,效果为:android:drawable="@drawable/ios7_switch_on"

反之就是未选中off情况下的效果:android:drawable="@drawable/ios7_switch_off"

也不要说曾经失去,失去的不是永远失去,得到的不是永远拥有,

SwitchButton 开关按钮 的多种实现方式 (附源码DEMO)

相关文章:

你感兴趣的文章:

标签云: