LVGL V7版本 按键 切换 焦点控件的实现
在 LVGL(Light and Versatile Graphics Library)中,管理焦点控件的切换通常涉及到使用按键事件来改变当前焦点控件。以下是一个简单的示例,展示如何在 LVGL V7 中实现按键切换焦点控件的功能。
#include "lvgl/lvgl.h"
static lv_obj_t *btn1;
static lv_obj_t *btn2;
static lv_obj_t *btn3;
static lv_obj_t *current_focus = NULL;
static void btn_event_handler(lv_event_t * e) {
lv_obj_t * btn = lv_event_get_target(e);
lv_obj_set_style_bg_color(btn, lv_color_hex(0x00FF00), LV_PART_MAIN); // 设置选中颜色
if (current_focus != NULL && current_focus != btn) {
lv_obj_set_style_bg_color(current_focus, lv_color_hex(0xFFFFFF), LV_PART_MAIN); // 恢复未选中颜色
}
current_focus = btn;
}
static void keyboard_event_handler(lv_event_t * e) {
lv_indev_t * indev = lv_event_get_indev(e);
lv_indev_type_t type = lv_indev_get_type(indev);
if (type == LV_INDEV_TYPE_KEYPAD) {
lv_keypad_key_t key = lv_indev_get_key(indev);
if (key == LV_KEY_UP) {
// 切换到上一个控件
if (current_focus == btn1) {
current_focus = btn3;
} else if (current_focus == btn2) {
current_focus = btn1;
} else if (current_focus == btn3) {
current_focus = btn2;
}
} else if (key == LV_KEY_DOWN) {
// 切换到下一个控件
if (current_focus == btn1) {
current_focus = btn2;
} else if (current_focus == btn2) {
current_focus = btn3;
} else if (current_focus == btn3) {
current_focus = btn1;
}
}
// 更新焦点
btn_event_handler(e);
}
}
void create_ui() {
lv_obj_t * scr = lv_scr_act();
btn1 = lv_btn_create(scr);
lv_obj_set_pos(btn1, 10, 10);
lv_obj_set_size(btn1, 100, 50);
lv_obj_add_event_cb(btn1, btn_event_handler, LV_EVENT_CLICKED, NULL);
btn2 = lv_btn_create(scr);
lv_obj_set_pos(btn2, 10, 70);
lv_obj_set_size(btn2, 100, 50);
lv_obj_add_event_cb(btn2, btn_event_handler, LV_EVENT_CLICKED, NULL);
btn3 = lv_btn_create(scr);
lv_obj_set_pos(btn3, 10, 130);
lv_obj_set_size(btn3, 100, 50);
lv_obj_add_event_cb(btn3, btn_event_handler, LV_EVENT_CLICKED, NULL);
// 初始化焦点
current_focus = btn1;
btn_event_handler(NULL); // 设置初始焦点样式
}
int main(void) {
lv_init();
// 初始化显示和输入设备
// ...
create_ui();
while (1) {
lv_task_handler();
// 处理输入设备
// ...
}
return 0;
}
create_ui
函数中创建了三个按钮,并为每个按钮添加了事件处理函数。current_focus
变量来跟踪当前的焦点控件。每当按钮被点击或按键事件发生时,都会更新这个变量。keyboard_event_handler
函数中,根据按键的上下方向切换焦点控件,并调用 btn_event_handler
更新样式。btn_event_handler
中,根据当前焦点控件的状态更新按钮的背景颜色。