I needed to create a view dynamically and that was working ok. Then I wanted to add some text beneath that view and I couldn’t get it to work: the text appeared over the top of the first view. The solution for me was to set in code the id of the first view.
Code in activity:
RelativeLayout.LayoutParams lpr, lpr2;
TextView tip;
ViewPager vp;
...
lpr = new RelativeLayout.LayoutParams(drawingWidth, drawingWidth);
lpr.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
lpr.setMargins(10, 0, 0, 0);
vp = new ViewPager(this);
vp.setLayoutParams(lpr);
myLayoutr.addView(vp);
vp.setId(R.id.reservedNamedId); //THIS IS THE LINE THAT FIXED IT
lpr2 = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lpr2.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
lpr2.addRule(RelativeLayout.BELOW, vp.getId());
lpr.setMargins(10, 0, 0, 0);
tip = new TextView(this);
tip.setText(R.string.gallery_tip);
tip.setLayoutParams(lpr2);
myLayoutr.addView(tip);
This needs ids.xml to be created in values folder.
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="reservedNamedId" type="id"/>
<item name="reservedNamedId2" type="id"/>
<item name="reservedNamedId3" type="id"/>
</resources>