介绍
状态开关按钮(Switch)也是由 Button 派生出来的,所以在本质上它也算是一个比较高级的按钮,用户可以来回拖动“拇指”控制该按钮的开启与关闭或者只需轻按,就像选择复选框一样来开启该组件。在 Android 中,该组件经常被使用到 App 的设置界面当中。
基本语法:
<Switch
android:id=”@+id/ID号"
android:layout_width=”wrap_content”
android:layout_height=”wrap_content” />
XML属性
XML属性 | 描述 |
android:switchMinWidth | 设置开关组件的最小宽度 |
android:switchPadding | 设置开关组件与左侧标题文本之间的距离 |
android:switchTextAppearance | 设置开关组件标题文本的样式 |
android:textOff | 设置开关组件关闭时显示的文本 |
android:textOn | 设置开关组件开启时显示的文本 |
android:showText | 是否显示该组件打开或关闭时所显示的文本 |
android:textStyle | 设置开关组件的文本风格 |
android:thumb | 指定该组件切换开关的图标 |
android:track | 指定该组件开关滑动的轨道 |
例子
模拟横屏模式的开关
编写布局文件
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!--状态开关-->
<Switch
android:id="@+id/sw"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="75dp"
android:text="开启横屏模式"
android:textColor="#000000"
android:switchPadding="170dp"
android:layout_marginLeft="13dp"/>
</RelativeLayout>
编写SwitchActivity
public class SwitchActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN); //设置全屏显示
final Switch switch1= (Switch) findViewById(R.id.sw); //获取布局文件中switch开关组件
//设置开关状态改变监听器
switch1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if (switch1.isChecked()){ //判断状态开关是否被选中
Toast.makeText(SwitchActivity.this, "开启横屏模式!", Toast.LENGTH_SHORT).show();
}else {
Toast.makeText(SwitchActivity.this, "关闭横屏模式!", Toast.LENGTH_SHORT).show();
}
}
});
}
}
效果