试试这个:
for (int i = 0; i < someNumber; i++) {
LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // or any other layout params that suit your needs
LinearLayout childContainer = new LinearLayout(this);
parentLayout.addView(childContainer, params)
}
编辑
考虑你需要使用的XML内容,你会需要创建一个自定义类来扩展LinearLayout并在其中初始化其所有属性。喜欢的东西:
public class MyLinearLayout extends LinearLayout {
public MyLinearLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
public MyLinearLayout(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public MyLinearLayout(Context context) {
super(context);
init(context);
}
private void init(Context context) {
inflate(context, R.id.R.layout.child_container, this);
// setup all your Views from here with calls to getViewById(...);
}
}
此外,由于您的自定义LieanrLayout从LinearLayout中伸出您可以通过<merge>
更换根<LinearLayout>
元素优化的XML。这是一个short documentation和一个SO link。因此,for循环变为:
for (int i = 0; i < someNumber; i++) {
LinearLayout.LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); // or any other layout params that suit your needs
LinearLayout childContainer = new MyLinearLayout(this);
parentLayout.addView(childContainer, params); // feel free to add or not the LayoutParams object
}
是的,这应该工作。如果您的子容器布局特别复杂(大量子视图/选项),那么您始终可以使用扩展LinearLayout的类来设置您的child_container xml setContentView()并实例化该类,如此处所示。 –
@gunar但是我的childContainer的实际内容呢。我需要它包含来自xml的内容。 – user2426316
嗯......错过了那部分! :D让我想想 – gunar