1 #include "../../lv_examples.h"
2 #if LV_USE_CHECKBOX && LV_BUILD_EXAMPLES
3
4 static lv_style_t style_radio;
5 static lv_style_t style_radio_chk;
6 static uint32_t active_index_1 = 0;
7 static uint32_t active_index_2 = 0;
8
radio_event_handler(lv_event_t * e)9 static void radio_event_handler(lv_event_t * e)
10 {
11 uint32_t * active_id = lv_event_get_user_data(e);
12 lv_obj_t * cont = lv_event_get_current_target(e);
13 lv_obj_t * act_cb = lv_event_get_target(e);
14 lv_obj_t * old_cb = lv_obj_get_child(cont, *active_id);
15
16 /*Do nothing if the container was clicked*/
17 if(act_cb == cont) return;
18
19 lv_obj_clear_state(old_cb, LV_STATE_CHECKED); /*Uncheck the previous radio button*/
20 lv_obj_add_state(act_cb, LV_STATE_CHECKED); /*Uncheck the current radio button*/
21
22 *active_id = lv_obj_get_index(act_cb);
23
24 LV_LOG_USER("Selected radio buttons: %d, %d", (int)active_index_1, (int)active_index_2);
25 }
26
radiobutton_create(lv_obj_t * parent,const char * txt)27 static void radiobutton_create(lv_obj_t * parent, const char * txt)
28 {
29 lv_obj_t * obj = lv_checkbox_create(parent);
30 lv_checkbox_set_text(obj, txt);
31 lv_obj_add_flag(obj, LV_OBJ_FLAG_EVENT_BUBBLE);
32 lv_obj_add_style(obj, &style_radio, LV_PART_INDICATOR);
33 lv_obj_add_style(obj, &style_radio_chk, LV_PART_INDICATOR | LV_STATE_CHECKED);
34 }
35
36 /**
37 * Checkboxes as radio buttons
38 */
lv_example_checkbox_2(void)39 void lv_example_checkbox_2(void)
40 {
41 /* The idea is to enable `LV_OBJ_FLAG_EVENT_BUBBLE` on checkboxes and process the
42 * `LV_EVENT_CLICKED` on the container.
43 * A variable is passed as event user data where the index of the active
44 * radiobutton is saved */
45
46 lv_style_init(&style_radio);
47 lv_style_set_radius(&style_radio, LV_RADIUS_CIRCLE);
48
49 lv_style_init(&style_radio_chk);
50 lv_style_set_bg_img_src(&style_radio_chk, NULL);
51
52 uint32_t i;
53 char buf[32];
54
55 lv_obj_t * cont1 = lv_obj_create(lv_scr_act());
56 lv_obj_set_flex_flow(cont1, LV_FLEX_FLOW_COLUMN);
57 lv_obj_set_size(cont1, lv_pct(40), lv_pct(80));
58 lv_obj_add_event_cb(cont1, radio_event_handler, LV_EVENT_CLICKED, &active_index_1);
59
60 for(i = 0; i < 5; i++) {
61 lv_snprintf(buf, sizeof(buf), "A %d", (int)i + 1);
62 radiobutton_create(cont1, buf);
63
64 }
65 /*Make the first checkbox checked*/
66 lv_obj_add_state(lv_obj_get_child(cont1, 0), LV_STATE_CHECKED);
67
68 lv_obj_t * cont2 = lv_obj_create(lv_scr_act());
69 lv_obj_set_flex_flow(cont2, LV_FLEX_FLOW_COLUMN);
70 lv_obj_set_size(cont2, lv_pct(40), lv_pct(80));
71 lv_obj_set_x(cont2, lv_pct(50));
72 lv_obj_add_event_cb(cont2, radio_event_handler, LV_EVENT_CLICKED, &active_index_2);
73
74 for(i = 0; i < 3; i++) {
75 lv_snprintf(buf, sizeof(buf), "B %d", (int)i + 1);
76 radiobutton_create(cont2, buf);
77 }
78
79 /*Make the first checkbox checked*/
80 lv_obj_add_state(lv_obj_get_child(cont2, 0), LV_STATE_CHECKED);
81 }
82
83 #endif
84