系统自带的ToggleButton通常都不能满足我们的审美需求,因此需要我们自定义自己的ToggleButton。
运行效果如图:
工程的目录结构图:
布局文件:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="系统的toggleButton" />
<ToggleButton
android:id="@+id/toggleButton1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:checked="false" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="自定义的toggleButton" />
<ToggleButton
android:id="@+id/togglebutton2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/btn_toggle"
android:checked="false"
android:text=""
android:textOff=""
android:textOn="" />
</LinearLayout>
</LinearLayout>
android:textOn="" 表示:选中情况下显示的文本
android:textOff="" 表示:未选中情况下显示的文本
android:checked="false" 表示:初始化时候,默认是未选中的
android:button="@drawable/toggle_btn" 表示:button样式
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:state_checked="false" android:drawable="@drawable/btn_toggle_no" />
<item android:state_checked="true" android:drawable="@drawable/btn_toggle_yes" />
</selector>
btn_toggle_bg.xml文件:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:id="@+android:id/background" android:drawable="@android:color/transparent" />
<item android:id="@+android:id/toggle" android:drawable="@drawable/btn_toggle" />
</layer-list>
源代码下载路径: http://download.csdn.net/detail/dangnianmingyue_gg/9150197