
1.添加按钮
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:id="@+id/tv1"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:padding="5dp"
android:text="Switch开关:">
</TextView>
<Switch
android:id="@+id/sw1"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_gravity="end">
</Switch>
</LinearLayout>
<TextView
android:id="@+id/tv2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="start"
android:layout_marginTop="10dp">
</TextView>
2.监听按钮变化
private TextView tv2;
tv2 = findViewById(R.id.tv2); Switch sw1 = findViewById(R.id.sw1); sw1.setOnCheckedChangeListener(this::onCheckedChange);
private void onCheckedChange(CompoundButton compoundButton, boolean b) {
String ss = String.format("Switch按钮的状态是%s",b?"开":"关");
if(b){
tv2.setText(ss);
}else {
tv2.setText(ss);
}
}
3.自定义
定义选择器:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true"
android:drawable="@drawable/s1">
</item>
<item android:drawable="@drawable/s2"></item>
</selector>
引用选择器:
<CheckBox
android:layout_width="80dp"
android:layout_height="30dp"
android:button="@null"
android:background="@drawable/switch_selector">
</CheckBox>
![]()










