So I have a relative layout on my activity and I'm trying to have my buttons be dynamically instantiated based on data in a text file. The data is being read correctly and each button is being instantiated but only the first one instantiates correctly, all other buttons instantiate above the first button in the same position, overlapping each other. Code I am using:
RelativeLayout layout = (RelativeLayout)findViewById(R.id.relLayout);
Resources r = getResources();
float px = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 400, r.getDisplayMetrics());
int prevId = 0;
for(int i = 0; i < data.size(); i++) {
Button btn = new Button(this);
btn.setText(data.get(i).substring(0, data.get(i).indexOf(',')));
btn.setWidth((int) px);
btn.setId(i);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if(i > 0) {
params.addRule(RelativeLayout.BELOW, prevId);
} else {
params.addRule(RelativeLayout.BELOW, findViewById(R.id.addClass).getId());
}
layout.addView(btn, params);
prevId = btn.getId();
}
The only difference I can see between the first and other buttons is that the first button sets its position relative to a static anchor I have while the other buttons alignments are anchored by the previous button. (Or well, supposed to be). It should end of in the following format:
Classes
Add Class (static button)
dynamicbutton1
dynamicbutton2
. . .