LVGL_基础控件Switch_Button
1、创建switch_button
![LVGL_基础控件Switch_Button_第1张图片](http://img.e-com-net.com/image/info8/6f082961b5754662b53ea58cfcb77aea.jpg)
lv_obj_t * sw = lv_switch_create(lv_scr_act());
lv_obj_center(sw);
2、修改未选中背景颜色
![LVGL_基础控件Switch_Button_第2张图片](http://img.e-com-net.com/image/info8/b9e10dc7b8174a31bfde5faf0597cdee.jpg)
![LVGL_基础控件Switch_Button_第3张图片](http://img.e-com-net.com/image/info8/0e67a3c5ef8242cfb31e16527abf54ff.jpg)
lv_obj_set_style_bg_color(sw, lv_color_hex(0xc43e1c), LV_PART_MAIN);
3、修改盒子内颜色大小
![LVGL_基础控件Switch_Button_第4张图片](http://img.e-com-net.com/image/info8/d2a8138a9d8841239a322fd372a96ddb.jpg)
![LVGL_基础控件Switch_Button_第5张图片](http://img.e-com-net.com/image/info8/6863ea97800149cf9f1c3398c4aa746c.jpg)
lv_obj_set_style_pad_all(sw, 5, LV_PART_MAIN);
lv_obj_set_style_pad_left(sw, 10, LV_PART_MAIN);
4、设置背景透明度和背景颜色
lv_obj_set_style_bg_opa(sw, 10, LV_PART_INDICATOR);
lv_obj_set_style_bg_color(sw, lv_color_hex(0xc43e1c), LV_PART_INDICATOR);
5、修改选中状态下的控件背景色
![LVGL_基础控件Switch_Button_第6张图片](http://img.e-com-net.com/image/info8/ebfee2ee307448f9ad150629a21aff2e.jpg)
lv_obj_set_style_bg_color(sw, lv_color_hex(0x7719aa), LV_PART_INDICATOR | LV_STATE_CHECKED);
6、修改中间旋钮的颜色
![LVGL_基础控件Switch_Button_第7张图片](http://img.e-com-net.com/image/info8/3cc505dcbcf1463cafdf0e13e062d45e.jpg)
lv_obj_set_style_bg_color(sw, lv_color_hex(0xc43e1c), LV_PART_KNOB);
7、修改控件大小
![LVGL_基础控件Switch_Button_第8张图片](http://img.e-com-net.com/image/info8/bc4091d1291b4d6fad9a0f69818a5c4a.jpg)
lv_obj_set_size(sw, 200, 100);
8、默认让控件处于选中的状态
lv_obj_clear_state(sw, LV_STATE_CHECKED);
lv_obj_add_state(sw, LV_STATE_CHECKED);
9、让控件保持当前状态不允许更改
![LVGL_基础控件Switch_Button_第9张图片](http://img.e-com-net.com/image/info8/abf24f5476464f5fa0e606da7f756549.jpg)
lv_obj_clear_state(sw, LV_STATE_CHECKED);
lv_obj_add_state(sw, LV_STATE_DISABLED);
![LVGL_基础控件Switch_Button_第10张图片](http://img.e-com-net.com/image/info8/4839398b6bb04e05af7f100d1e5d597f.jpg)
lv_obj_add_state(sw, LV_STATE_CHECKED | LV_STATE_DISABLED);
10、添加事件
lv_obj_add_event_cb(sw, sw_event_handler, LV_EVENT_VALUE_CHANGED, NULL);
static void sw_event_handler(lv_event_t * e)
{
lv_event_code_t code = lv_event_get_code(e);
lv_obj_t *sw = lv_event_get_target(e);
if (code == LV_EVENT_VALUE_CHANGED)
{
LV_LOG_USER("State: %s", lv_obj_has_state(sw, LV_STATE_CHECKED) ? "ON" : "OFF");
}
}
11、清除禁用状态
lv_obj_clear_state(sw, LV_STATE_DISABLED);
12、按键控制逻辑
![LVGL_基础控件Switch_Button_第11张图片](http://img.e-com-net.com/image/info8/8d455c622d2849a9a2c3636330c0e376.jpg)