问题
I'm trying to add multiple layouts dynamically under each other. So I wrote the following code:
for (int i = 1; i <= layoutCounter; i++) {
View neu = inflater.inflate(R.layout.vote, parent, false);
neu.setId(layoutID);
if (layoutID == 1) {
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, R.id.txtMultiline);
} else {
params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.BELOW, neu.getId());
}
neu.setLayoutParams(params);
parent.addView(neu);
layoutID++;
}
txtMultiline is a fixed View defined in XML. LayoutID is an integer and starts with 1. The first layout is added correctly under the txtMultiline TextView. But all following layouts just get added on top of the parent layout (which is a RelativeLayout). Can't get the reason.. else-route is executed correctly. But the BELOW constant seems to have no effect when trying to apply it to my dynamically inflated layouts. What am I doing wrong?
回答1:
Maybe with:
params.addRule(RelativeLayout.BELOW, layoutID-1);
instead of:
params.addRule(RelativeLayout.BELOW, neu.getId());
in your else condition.
回答2:
You can try like this
RelativeLayout.LayoutParams rl = new RelativeLayout.LayoutParams(...)
rl.addRule(RelativeLayout.BELOW, anotherview.getId())
rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT)
parentLayout.addView(myView, rl)
来源:https://stackoverflow.com/questions/14139214/android-dynamically-add-layouts-under-each-other