image.png
按钮矩阵(lv_btnmatrix)组件是一种在行和列中显示多个按钮的轻量级实现方式。按钮不是实际创建出来的,而是实时绘制出来的,所以轻量级。

1.常用方法

创建按钮矩阵:

  1. lv_obj_t * lv_btnmatrix_create(lv_obj_t * parent)

设置字符串数组:

  1. void lv_btnmatrix_set_map(lv_obj_t * obj, const char * map[])

参数1:btnmatrix对象 参数2:字符串数组,每个字符串代表一个按钮

设置按钮大小:

  1. void lv_btnmatrix_set_btn_width(lv_obj_t * obj, uint16_t btn_id, uint8_t width)

参数2:btn的编号(从0开始) 参数3:宽度的倍数(同行相比)

设置按钮的控制状态:

  1. void lv_btnmatrix_set_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)
  2. void lv_btnmatrix_clear_btn_ctrl(lv_obj_t * obj, uint16_t btn_id, lv_btnmatrix_ctrl_t ctrl)

btnmatrix事件处理:

  1. 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,
  2. void * user_data)

2.代码实现

  1. static const char *map[] = {"0","1","2","3","4","\n","5","6","7","8","9","\n","back","Enter",""};
  2. void event_handler2(lv_event_t* e){
  3. // 获取触发的事件码
  4. int code = lv_event_get_code(e);
  5. lv_obj_t* target = lv_event_get_target(e);
  6. if(code == LV_EVENT_VALUE_CHANGED){
  7. uint16_t selected_btn_index = lv_btnmatrix_get_selected_btn(target);
  8. const char* text = lv_btnmatrix_get_btn_text(target,selected_btn_index);
  9. printf("target: %p ,selceted:%d ,text:%s\n",target,selected_btn_index,text);
  10. printf("clicked\n");
  11. }
  12. }
  13. void demo5(){
  14. // 创建矩阵按钮
  15. lv_obj_t* btnm = lv_btnmatrix_create(lv_scr_act());
  16. // 设置矩阵按钮的显示
  17. lv_btnmatrix_set_map(btnm,map);
  18. lv_obj_set_width(btnm,220);
  19. lv_obj_align(btnm,LV_ALIGN_CENTER,0,0);
  20. // 设置按钮宽度
  21. //lv_btnmatrix_set_btn_width(btnm,1,3);
  22. // 回调函数
  23. lv_obj_add_event_cb(btnm,event_handler2,LV_EVENT_ALL,NULL);
  24. }

image.png