如何使用另一个布局的新实例来填充布局?

4
我希望能够在一个LinearLayout中填充多个另一个LinearLayout的实例。我该怎么做? 我的问题是,似乎我总是使用相同的实例,因此一遍又一遍地添加该实例。
简而言之: 我需要一种方法将LinearLayout子项的新实例添加到另一个LinearLayout父项中。
到目前为止,我已经做了以下工作:
private void setupContainers() {
    LayoutInflater layoutInflater = (LayoutInflater)this.getSystemService(MainActivity.LAYOUT_INFLATER_SERVICE);
    LinearLayout parentContainer = (LinearLayout)this.findViewById(R.id.parent_container);

    for (int i = 0; i < someNumber; i++) {

        LinearLayout childContainer = (LinearLayout) layoutInflater.inflate(R.layout.child_container, null);
        parentContainer.addView(childContainer);

    }
}
1个回答

4

试试这个:

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,您可以通过将根元素替换为来优化xml。这里有一个简短文档和一个SO链接。因此,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的类,使用setContentView()设置您的child_container xml,并像这里所示实例化该类。 - Andrew G
@gunar 但是我的 childContainer 实际内容怎么办?我需要它包含来自 XML 的内容。 - user2426316
嗯...错过了那部分! :D 让我想想。 - gunar
就像Andrew所说的那样:您需要创建一个自定义类,该类从LinearLayout继承并从xml中填充。我会很快更新答案。 - gunar

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接