目前遇到一个问题,想知道如何通过非全局变量创建label和不通过按钮传递参数(因为代码层级太多了不方便传递)的方式,实现char*数值修改label的文本,并刷新界面。以下是demo代码:
char* a= "icon 1";
char* b= "icon 2";
// 按钮点击事件处理函数
void btn1_event_handler(lv_obj_t* obj, lv_event_t event) {
if (event == LV_EVENT_CLICKED) {
// 从按钮的用户数据中获取标签指针
if(a== "icon 1"){
a= "icon 2";
b= "icon 1";
}else{
a= "icon 1";
b= "icon 2";
}
printf("a:%s\n",a);
printf("b:%s\n",b);
}
}
void lv_demo_refresh(lv_obj_t* obj) {
LV_IMG_DECLARE(aaa);
LV_IMG_DECLARE(bbb);
// 将背景改为黑色
lv_obj_set_style_local_bg_color(obj, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000));
lv_obj_t* page_q = lv_page_create(obj, NULL);
lv_obj_set_size(page_q, WATCHAI_UI_WIDTH, WATCHAI_UI_HEIGHT);
lv_obj_set_style_local_bg_color(page_q, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0x000000));
// 创建第一个图标和标签
lv_obj_t* icon1 = lv_img_create(page_q, NULL);
lv_img_set_src(icon1, &aaa);
lv_obj_align(icon1, NULL, LV_ALIGN_IN_TOP_LEFT, 0, 20);
lv_img_set_zoom(icon1, 128);
lv_obj_set_style_local_radius(icon1, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_RADIUS_CIRCLE);
// 创建文本标签label1
lv_obj_t* label1 = lv_label_create(page_q, NULL);
lv_label_set_text(label1, a); // 初始化label1文本
lv_obj_align(label1, icon1, LV_ALIGN_IN_BOTTOM_MID, 0, 0);
lv_obj_set_style_local_text_color(label1, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0xffffff));
// 创建第二个图标和标签
lv_obj_t* icon2 = lv_img_create(page_q, NULL);
lv_img_set_src(icon2, &bbb);
lv_obj_align(icon2, NULL, LV_ALIGN_IN_TOP_RIGHT, 0, 20);
lv_img_set_zoom(icon2, 128);
// 创建文本标签label2
lv_obj_t* label2 = lv_label_create(page_q, NULL);
lv_label_set_text(label2, b); // 初始化label2文本
lv_obj_align(label2, icon2, LV_ALIGN_IN_BOTTOM_MID, 0, 0);
lv_obj_set_style_local_text_color(label2, LV_LABEL_PART_MAIN, LV_STATE_DEFAULT, lv_color_hex(0xffffff));
// 创建按钮
lv_obj_t* btn1 = lv_btn_create(obj, NULL);
lv_obj_set_size(btn1, 100, 50);
lv_obj_align(btn1, NULL, LV_ALIGN_IN_BOTTOM_LEFT, 20, 0);
lv_obj_set_event_cb(btn1, btn1_event_handler);
// 创建按钮标签
lv_obj_t* button_label = lv_label_create(btn1, NULL);
lv_label_set_text(button_label, "Swap Labels");
}
int main(int argc, char** argv) {
(void)argc; /*Unused*/
(void)argv; /*Unused*/
/*Initialize LVGL*/
lv_init();
/*Initialize the HAL (display, input devices, tick) for LVGL*/
hal_init();
lv_demo_refresh(lv_scr_act());
while (1) {
/* Periodically call the lv_task handler.
* It could be done in a timer interrupt or an OS task too.*/
lv_task_handler();
usleep(5 * 1000);
}
return 0;
}