Switch控件详解

时间:2022-05-19 08:37:50

Switch控件详解

原生效果

5.x

Switch控件详解

4.x

Switch控件详解

布局

<Switch
android:id="@+id/setting_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

属性

Attribute Name Related Method Description
android:showText setShowText(boolean) Whether to draw on/off text.
android:splitTrack setSplitTrack(boolean) Whether to split the track and leave a gap for the thumb drawable.
android:switchMinWidth setSwitchMinWidth(int) Minimum width for the switch component Must be a dimension value, which is a floating point number appended with a unit such as “14.5sp”.
android:switchPadding setSwitchPadding(int) Minimum space between the switch and caption text Must be a dimension value, which is a floating point number appended with a unit such as “14.5sp”.
android:switchTextAppearance setSwitchTextAppearance(Context,int) TextAppearance style for text displayed on the switch thumb.
android:textOff setTextOff(CharSequence) Text to use when the switch is in the unchecked/”off” state.
android:textOn setTextOn(CharSequence) Text to use when the switch is in the checked/”on” state.
android:textStyle setSwitchTypeface(Typeface) Style (bold, italic, bolditalic) for the text.
android:thumb setThumbResource(int) Drawable to use as the “thumb” that switches back and forth.
android:thumbTextPadding setThumbTextPadding(int) Amount of padding on either side of text within the switch thumb.
android:thumbTint setThumbTintList(ColorStateList) Tint to apply to the thumb.
android:thumbTintMode setThumbTintMode(PorterDuff.Mode) Blending mode used to apply the thumb tint.
android:track setTrackResource(int) Drawable to use as the “track” that the switch thumb slides within.
android:trackTint setTrackTintList(ColorStateList) Tint to apply to the track.
android:trackTintMode setTrackTintMode(PorterDuff.Mode) Blending mode used to apply the track tint.
android:typeface setSwitchTypeface(Typeface) Typeface (normal, sans, serif, monospace) for the text.

状态监听

Switch mSwitch = (android.widget.Switch) findViewById(R.id.setting_switch);
mSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
//选中时 do some thing
Toast.makeText(MainActivity.this, "enabled", Toast.LENGTH_SHORT).show();
} else {
//非选中时 do some thing
Toast.makeText(MainActivity.this, "disabled", Toast.LENGTH_SHORT).show();
}
}
});

设置开关状态显示的文字

Switch控件详解

<Switch
android:id="@+id/setting_switch"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:showText="true"
android:textOff="关"
android:textOn="开" />

设置最小显示宽度

android:switchMinWidth="50dp"