LVGL实现按钮互斥效果

效果

2022年8月29日-两个互斥按钮

实现代码

在你的代码中调用 lv_100ask_example_btn 函数:


 static void btn_event_handler(lv_event_t * e)
{
    lv_event_code_t code = lv_event_get_code(e);
    lv_obj_t * another_btn = (lv_obj_t *)lv_event_get_user_data(e);
    lv_obj_t * btn = lv_event_get_target(e);
    lv_obj_t * label = lv_obj_get_child(btn, 0);
    char * label_text = lv_label_get_text(label);

    if(code == LV_EVENT_CLICKED) {
        if((strcmp(label_text, "START") == 0)&&\
           (lv_obj_has_state(another_btn, LV_STATE_DISABLED))) {
            lv_obj_add_state(btn, LV_STATE_DISABLED);
            lv_obj_clear_state(another_btn, LV_STATE_DISABLED);
        }
        else if((strcmp(label_text, "STOP") == 0) &&\
                (lv_obj_has_state(another_btn, LV_STATE_DISABLED))) {
            lv_obj_clear_state(another_btn, LV_STATE_DISABLED);
            lv_obj_add_state(btn, LV_STATE_DISABLED);
        }
    }
}


static void lv_100ask_example_btn(void)
{
    lv_obj_t * label;

    lv_obj_t * btn1 = lv_btn_create(lv_scr_act());
    lv_obj_align(btn1, LV_ALIGN_CENTER, 0, -40);

    label = lv_label_create(btn1);
    lv_label_set_text(label, "START");
    lv_obj_center(label);

    lv_obj_t * btn2 = lv_btn_create(lv_scr_act());
    lv_obj_add_state(btn2, LV_STATE_DISABLED);
    lv_obj_align(btn2, LV_ALIGN_CENTER, 0, 40);

    label = lv_label_create(btn2);
    lv_label_set_text(label, "STOP");
    lv_obj_center(label);

    lv_obj_add_event_cb(btn1, btn_event_handler, LV_EVENT_ALL, btn2);
    lv_obj_add_event_cb(btn2, btn_event_handler, LV_EVENT_ALL, btn1);
}