I used to deal with common problems a year ago when I was working on a library for dynamically creating layouts from XML files (since Android does not support this). Therefore, when you dynamically add views to a RelativeLayout , you need to keep in mind a few things:
- Create a
View container (in this case, RelativeLayout ) - Create all views without assigning any layout options.
- Add all child views to the container.
- Iterate over the children of the container and populate each child layout. This is necessary because when relational constraints are applied,
Excpetion is created if there is no relative View (previously not added to the container).
This is an example of code taken from a project I was working on. Keep in mind that this is just one part, so it contains references to classes that are not defined in the Android API. I am sure this will give you the basic idea of dynamically creating a RelativeLayot :
private void setChildren(RelativeLayout layout, T widget, InflaterContext inflaterContext, Context context, Factory<Widget, View> factory) { List<Widget> children = widget.getChildren(); if (Utils.isEmpty(children))) { return; } // 1. create all children for (Widget child : children) { View view = factory.create(inflaterContext, context, child); layout.addView(view); } // 2. Set layout parameters. This is done all children are created // because there are relations between children. for (Widget child : children) { try { View view = ViewIdManager.getInstance().findViewByName(layout, child.getId()); if (view != null) { populateLayoutParmas(child, view); } } catch (IndexNotFoundException e) { Log.e(LOG_TAG, "Cannot find a related view for " + child.getId(), e); } } }
Kiril Aleksandrov
source share