user2426316
user2426316

Reputation: 7331

How can I inflate a layout with new instances of the another layout?

I would like to inflate a LinearLayout with multiple instances of another LinearLayout. How can I do that? My problem is that I seem to always use the same instance and hence add that instance over and over again.

In short: What I need is a way to add new instances of a LinearLayout child to another LinearLayout parent.

Here is what I have done so far:

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);

    }
}

Upvotes: 4

Views: 1636

Answers (1)

gunar
gunar

Reputation: 14720

Try this:

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)
}

EDIT

Considering you need to use the content from XML, you'll need to create a custom class that extends LinearLayout and initialize in there all its properties. Something like:

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(...);
    }

}

Also, since your custom LieanrLayout extends from LinearLayout you can optimize the xml by replacing the root <LinearLayout> element with <merge>. Here is a short documentation and an SO link. So the for loop becomes:

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
}

Upvotes: 4

Related Questions