[英]Dynamically Adding LinearLayouts in Android
I'm trying to add LinearLayouts dynamically but it's just not working. 我正在尝试动态添加LinearLayouts但它不起作用。 I think I just need another set of eyes to look it over. 我想我只需要另一组眼睛来看一遍。 Can anyone help me? 谁能帮我?
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
lLayout = new LinearLayout[8];
for(int i = 0; i < lLayout.length; i++) {
lLayout[i] = new LinearLayout(this);
lLayout[i].setId(i);
lLayout[i].setOrientation(LinearLayout.HORIZONTAL);
if(i%2 == 0) {
lLayout[i].setBackgroundColor(Color.GREEN);
} else {
lLayout[i].setBackgroundColor(Color.MAGENTA);
}
parentLayout.addView(lLayout[i]);
}
您需要设置LayoutParams,尝试添加以下内容:
lLayout[i].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
It looks like you are trying to make a listview yourself using linearlayouts rather than actually using the ListView already supported. 看起来您正在尝试使用线性布局自己制作列表视图,而不是实际使用已经支持的ListView。
If you are actually trying to do that, you should first give the layouts inside the view a width and height. 如果您确实尝试这样做,则应首先在视图中为布局提供宽度和高度。 I'd also put the list in a scrollview in case it overflows the outer layout. 我还将列表放在scrollview中,以防它溢出外部布局。
Maybe try this 也许试试这个
LinearLayout parentLayout = (LinearLayout)findViewById(R.id.parentLayout);
lLayout = new LinearLayout[8];
for(int i = 0; i < lLayout.length; i++) {
lLayout[i] = new LinearLayout(this);
lLayout[i].setId(i);
lLayout[i].setOrientation(LinearLayout.HORIZONTAL);
if(i%2 == 0) {
lLayout[i].setBackgroundColor(Color.GREEN);
} else {
lLayout[i].setBackgroundColor(Color.MAGENTA);
}
LinearLayout.LayoutParams myLayoutParams = new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
myLayoutParams.leftMargin = 0;
myLayoutParams.topMargin = 50 * i;
myLayoutParams.width = myScreenSize; //e.g. 480
myLayoutParams.height = 50;
lLayout[i].setLayoutParams(myLayoutParams);
parentLayout.addView(lLayout[i]);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.