Android基础控件ToggleButton和Switch开关按钮

时间:2023-03-09 01:30:54
Android基础控件ToggleButton和Switch开关按钮

1、简介

  ToggleButton和Switch都是开关按钮,只不过Switch要Android4.0之后才能使用!

ToggleButton
<!--checked 是否选择-->
<!--disabledAlpha 禁用时透明度-->
<!--textOn,textOff 打开/关闭时文字--> Switch
<!--checked 是否选择-->
<!--textOn,textOff 打开/关闭时文字-->
<!--showText 是否显示文字-->
<!--splitTrack 滑块是否和底部图片分隔-->
<!--switchMinWidth 最小宽度-->
<!--track 底部图片-->
<!--thumb 滑块图片-->
<!--typeface 字体四种-->

2、简单使用

Android基础控件ToggleButton和Switch开关按钮

  xml布局文件

        <ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="打开"
android:textOff="关闭"
android:id="@+id/toggle"
android:checked="true"
android:disabledAlpha=".5"
/> <!--textOn,textOff 打开/关闭时文字-->
<!--showText 是否显示文字-->
<!--splitTrack 滑块是否和底部图片分隔-->
<!--switchMinWidth 最小宽度-->
<!--track 底部图片-->
<!--thumb 滑块图片-->
<!--typeface 字体四种-->
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textOn="打开"
android:textOff="关闭"
android:showText="true"
android:splitTrack="false"
android:switchMinWidth="100dp"
android:typeface="serif"
android:id="@+id/switch11"
/>

  Java文件,点击事件处理:

        ToggleButton toggleButton = (ToggleButton)findViewById(R.id.toggle);
toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
Log.d("toggle","打开了");
}else {
Log.d("switch","关闭了");
}
}
}); final Switch switch1 = (Switch)findViewById(R.id.switch11);
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b){
Log.d("switch","开了");
}else {
Log.d("switch","关了"); }
}
});