I try to create 5 buttons below each other, but they appear on each other
ArrayList<Button> btn = new ArrayList<>();
for (int i=0; i<10; i++) {
Log.d("TEST", Integer.toString(i));
btn.add(new Button(this));
btn.get(i).setText(Integer.toString(i));
if (i == 0) {
btn.get(i).setLayoutParams(new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT));
} else {
RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
lp.addRule(RelativeLayout.BELOW, btn.get(i-1).getId());
btn.get(i).setLayoutParams(lp);
}
ll.addView(btn.get(i));
What is wrong with my code?
Solved by adding btn.get(i).setId(View.generateViewId()). All id of buttons was -1 before using setId().
From how you've named your layout, "ll", it seems you're adding those buttons to a LinearLayout. If that's the case, try changing that container layout to a RelativeLayout.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.