1、Switch 是什么?
简单:状态组件
官方:Switch是切换单个设置开/关两种状态的组件
2、简单使用
<Switch
ohos:id="$+id:btn_switch"
ohos:height="60vp"
ohos:width="100vp"
ohos:top_margin="50fp"
ohos:layout_alignment="center"
ohos:text_state_off="OFF"
ohos:text_state_on="ON"
/>
3、常用属性
(1)设置Switch在开启和关闭时的文本
<Switch
...
ohos:text_state_off="OFF"
ohos:text_state_on="ON"/>
Switch btnSwitch = (Switch) findComponentById(ResourceTable.Id_btn_switch);
btnSwitch.setStateOffText("OFF");
btnSwitch.setStateOnText("ON");
(2)设置响应Switch状态改变的事件
btnSwitch.setCheckedStateChangedListener(new AbsButton.CheckedStateChangedListener() {
// 回调处理Switch状态改变事件
@Override
public void onCheckedChanged(AbsButton button, boolean isChecked) {
}
});
3、实战:自定义Switch
<Switch
ohos:id="$+id:btn_switch"
ohos:height="60vp"
ohos:width="100vp"
ohos:top_margin="50fp"
ohos:layout_alignment="center"
ohos:text_state_off="OFF"
ohos:text_state_on="ON"
/>
public void onStart(Intent intent) {
super.onStart(intent);
super.setUIContent(ResourceTable.Layout_ability_main);
//创建shape实例,并设置样式
// 开启状态下滑块的样式
ShapeElement elementThumbOn = new ShapeElement();
elementThumbOn.setShape(ShapeElement.OVAL);
elementThumbOn.setRgbColor(RgbColor.fromArgbInt(0xFF1E90FF));
elementThumbOn.setCornerRadius(50);
// 关闭状态下滑块的样式
ShapeElement elementThumbOff = new ShapeElement();
elementThumbOff.setShape(ShapeElement.OVAL);
elementThumbOff.setRgbColor(RgbColor.fromArgbInt(0xFFFFFFFF));
elementThumbOff.setCornerRadius(50);
// 开启状态下轨迹样式
ShapeElement elementTrackOn = new ShapeElement();
elementTrackOn.setShape(ShapeElement.RECTANGLE);
elementTrackOn.setRgbColor(RgbColor.fromArgbInt(0xFF87CEFA));
elementTrackOn.setCornerRadius(50);
// 关闭状态下轨迹样式
ShapeElement elementTrackOff = new ShapeElement();
elementTrackOff.setShape(ShapeElement.RECTANGLE);
elementTrackOff.setRgbColor(RgbColor.fromArgbInt(0xFF808080));
elementTrackOff.setCornerRadius(50);
Switch btnSwitch = (Switch) findComponentById(ResourceTable.Id_btn_switch);
btnSwitch.setTrackElement(trackElementInit(elementTrackOn, elementTrackOff));
btnSwitch.setThumbElement(thumbElementInit(elementThumbOn, elementThumbOff));
}
//设置轨迹样式
private StateElement trackElementInit(ShapeElement on, ShapeElement off){
StateElement trackElement = new StateElement();
trackElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, on);
trackElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, off);
return trackElement;
}
//设置滑块样式
private StateElement thumbElementInit(ShapeElement on, ShapeElement off) {
StateElement thumbElement = new StateElement();
thumbElement.addState(new int[]{ComponentState.COMPONENT_STATE_CHECKED}, on);
thumbElement.addState(new int[]{ComponentState.COMPONENT_STATE_EMPTY}, off);
return thumbElement;
}