一、前言:很多app都有开关这个功能,开关控件的使用跟checkbox好像也差不多。
二、上代码
创建一个activity:SwitchDefaultActivity
public class SwitchDefaultActivity extends AppCompatActivity implements CompoundButton.OnCheckedChangeListener {
private Switch sw_status;
private TextView tv_result;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_switch_default);
sw_status = findViewById(R.id.sw_status);
tv_result = findViewById(R.id.tv_result);
sw_status.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String desc = String.format("Swith按钮的状态是%s",b ? "开":"关");
tv_result.setText(desc);
}
}
对应的xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp"
tools:context=".switchpg.SwitchDefaultActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="0dp"
android:layout_height="wrap_content"
android:text="Switch开关"
android:layout_weight="1"
android:layout_gravity="start"
android:padding="5dp"/>
<Switch
android:id="@+id/sw_status"
android:layout_width="80dp"
android:layout_height="30dp"
android:layout_gravity="end"/>
</LinearLayout>
<TextView
android:id="@+id/tv_result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="start"
android:layout_marginTop="10dp"/>
</LinearLayout>
三、效果展示