1
2# Fragment
3
4Fragment is a concept copied from [Android](https://developer.android.com/guide/fragments).
5
6It represents a reusable portion of your app's UI. A fragment defines and manages its own layout, has its own lifecycle,
7and can handle its own events. Like Android's Fragment that must be hosted by an activity or another fragment, Fragment
8in LVGL needs to be hosted by an object, or another fragment. The fragment’s view hierarchy becomes part of, or attaches
9to, the host’s view hierarchy.
10
11Such concept also has some similarities
12to [UiViewController on iOS](https://developer.apple.com/documentation/uikit/uiviewcontroller).
13
14Fragment Manager is a manager holding references to fragments attached to it, and has an internal stack to achieve
15navigation. You can use fragment manager to build navigation stack, or multi pane application easily.
16
17## Usage
18
19Enable `LV_USE_FRAGMENT` in `lv_conf.h`.
20
21### Create Fragment Class
22
23```c
24struct sample_fragment_t {
25    /* IMPORTANT: don't miss this part */
26    lv_fragment_t base;
27    /* States, object references and data fields for this fragment */
28    const char *title;
29};
30
31const lv_fragment_class_t sample_cls = {
32        /* Initialize something needed */
33        .constructor_cb = sample_fragment_ctor,
34        /* Create view objects */
35        .create_obj_cb = sample_fragment_create_obj,
36        /* IMPORTANT: size of your fragment struct */
37        .instance_size = sizeof(struct sample_fragment_t)
38};
39```
40
41### Use `lv_fragment_manager`
42
43```c
44/* Create fragment instance, and objects will be added to container */
45lv_fragment_manager_t *manager = lv_fragment_manager_create(container, NULL);
46/* Replace current fragment with instance of sample_cls, and init_argument is user defined pointer */
47lv_fragment_manager_replace(manager, &sample_cls, init_argument);
48```
49
50### Fragment Based Navigation
51
52```c
53/* Add one instance into manager stack. View object of current fragment will be destroyed,
54 * but instances created in class constructor will be kept.
55 */
56lv_fragment_manager_push(manager, &sample_cls, NULL);
57
58/* Remove the top most fragment from the stack, and bring back previous one. */
59lv_fragment_manager_pop(manager);
60```
61
62## Example
63
64```eval_rst
65
66.. include:: ../../examples/others/fragment/index.rst
67
68```
69
70## API
71
72```eval_rst
73
74.. doxygenfile:: lv_fragment.h
75  :project: lvgl
76
77```
78