按钮矩阵(lv_btnmatrix)组件是一种在行和列中显示多个按钮的轻量级实现方式。按钮不是实际创建出来的,而是实时绘制出来的,所以轻量级。
1.常用方法
创建按钮矩阵:
lv_obj_t * lv_btnmatrix_create(lv_obj_t * parent)
设置字符串数组:
void lv_btnmatrix_set_map(lv_obj_t * obj, const char * map[])
参数1:btnmatrix对象 参数2:字符串数组,每个字符串代表一个按钮
设置按钮大小:
void lv_btnmatrix_set_btn_width(lv_obj_t * obj, uint16_t btn_id, uint8_t width)
参数2:btn的编号(从0开始) 参数3:宽度的倍数(同行相比)
设置按钮的控制状态:
void lv_btnmatrix_set_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)
void lv_btnmatrix_clear_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)
btnmatrix事件处理:
struct _lv_event_dsc_t * lv_obj_add_event_cb(lv_obj_t * obj, lv_event_cb_t event_cb, lv_event_code_t filter,
void * user_data)
2.代码实现
static const char *map[] = {"0","1","2","3","4","\n","5","6","7","8","9","\n","back","Enter",""};
void event_handler2(lv_event_t* e){
// 获取触发的事件码
int code = lv_event_get_code(e);
lv_obj_t* target = lv_event_get_target(e);
if(code == LV_EVENT_VALUE_CHANGED){
uint16_t selected_btn_index = lv_btnmatrix_get_selected_btn(target);
const char* text = lv_btnmatrix_get_btn_text(target,selected_btn_index);
printf("target: %p ,selceted:%d ,text:%s\n",target,selected_btn_index,text);
printf("clicked\n");
}
}
void demo5(){
// 创建矩阵按钮
lv_obj_t* btnm = lv_btnmatrix_create(lv_scr_act());
// 设置矩阵按钮的显示
lv_btnmatrix_set_map(btnm,map);
lv_obj_set_width(btnm,220);
lv_obj_align(btnm,LV_ALIGN_CENTER,0,0);
// 设置按钮宽度
//lv_btnmatrix_set_btn_width(btnm,1,3);
// 回调函数
lv_obj_add_event_cb(btnm,event_handler2,LV_EVENT_ALL,NULL);
}