Lv_obj_add_style and memory usage


I have array of buttons and on click event I change button color by adding style.

static void event_handler(lv_obj_t* obj, lv_event_t event)
  lv_obj_add_style(obj, LV_OBJ_PART_MAIN, &style_home);

It looks like this procedure takes some memory. Since I have many clicks and low memory it is critical for me. Why setting style decrease memory?

Instead of changing style (in callback function) every time the button is pressed, you should initialize the button ahead for the “default” and “pressed” states ONCE.

See documentation: Button (lv_btn) — LVGL documentation
(list of styles: Styles — LVGL documentation )

See C example:

lv_obj_add_style(btn1, &style_pr, LV_STATE_PRESSED);

I hope this helps.

I need to change button color according to some external condition and leave button color till next press.

Ok, then maybe using lv_obj_set_style_bg_color for both ‘default’ and ‘pressed’ states?
It overwrites existing style bg_color instead of adding new style.
But in this case every button should have their own style objects (created before buttons are created). With this solution memory (for style objects) is allocated only once (when buttons are created), instead of every click event.

1 Like

It might work, but why lv_obj_add_style increases memory usage in general?

As I see in source code, it adds the new style object (pointer) to the object’s styles list, so the list (memory) size needs to be increased.
Source code: