Duplicate Views on Android during Run-time

Marcus picture Marcus · Feb 10, 2013 · Viewed 12.4k times · Source

I have created a Layout file for an activity. In this layout I have created a LinearLayout with a textview and an edittext. Now I want to create additional LinearLayouts that will look and contain the exact same views that my original LinearLayout, but with different texts. I also want to do it programmatically during run because the amount of these LinearLayout will vary between runs. I've read some about inflaters but I don't understand them enough to use them.

I'm thinking something like this, obviously the code is wrong, but hopefully you understand what I want to do:

LinearLayout llMain = (LinearLayout)findViewById(R.id.mainLayout);
LinearLayout llToCopy = (LinearLayout)findViewById(R.id.linearLayoutToCopy);
for(int player = 0; player < size; player++)
{
   LinearLayout llCopy = llToCopy.clone();
   TextView tv = (TextView)llCopy.getChildAt(0);
   tv.setText(players.get(player).getName());
   llMain.addView(llCopy);
}

Answer

jenzz picture jenzz · Feb 10, 2013

There are several ways to accomplish this.
A quick and easy approach is to inflate a new layout in every iteration of the loop:

LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout parent = (LinearLayout) inflater.inflate(R.layout.main, null);

for (int i = 0; i < 10; i++) {
    View child = inflater.inflate(R.layout.child, null);
    TextView tv = (TextView) child.findViewById(R.id.text);
    tv.setText("Child No. " + i);
    parent.addView(child);
}

setContentView(parent);

Another (more elegant) solution is to create a separate class extending LinearLayout:

public class ChildView extends LinearLayout {

    private TextView tv;

    public ChildView(Context context) {
        super(context);

        View.inflate(context, R.layout.child, this);
        tv = (TextView) findViewById(R.id.text);
    }

    public void setText(String text) {
        tv.setText(text);
    }
}

Now you can create a ChildView in every iteration of your loop and set the text via the setText(String text) method:

for (int i = 0; i < 10; i++) {
    ChildView child = new ChildView( this );
    child.setText("Child No. " + i);
    parent.addView(child);
}