Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: Add two text views programmatically

I am trying to add Views to a linear layout programmatically.

    LinearLayout layout     = (LinearLayout) findViewById(R.id.info);
    String [] informations  = topOffer.getInformations();
    TextView informationView;
    View line = new View(this);
    line.setLayoutParams(new LayoutParams(1, LayoutParams.FILL_PARENT));
    line.setBackgroundColor(R.color.solid_history_grey);
    for (int i = 0; i < informations.length; i++) {
        informationView = new TextView(this);
        informationView.setText(informations[i]);
        layout.addView(informationView, 0);
        layout.addView(line, 1);
    }

First, I have only added the informationsView, and everything worked fine. Butt after adding also the line-View, it crashed with the following error:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

So I tried addView(View v, int index), but it crashed with the same message...

Has somebody a solution?

Thanks, Martin

like image 618
Martin Avatar asked Jul 09 '10 07:07

Martin


2 Answers

As gpmoo7 said you need to create every time a new view in the loop

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.linear);

    LinearLayout layout = (LinearLayout) findViewById(R.id.linear);

    String[] informations = new String[] { "one", "two", "three" };
    TextView informationView;

    for (int i = 0; i < informations.length; i++) {
        View line = new View(this);
        line.setLayoutParams(new LayoutParams(1, LayoutParams.MATCH_PARENT));
        line.setBackgroundColor(0xAA345556);
        informationView = new TextView(this);
        informationView.setText(informations[i]);
        layout.addView(informationView, 0);
        layout.addView(line, 1);
    }

}
like image 136
vsm Avatar answered Nov 01 '22 16:11

vsm


You can't add the same child view multiple times in the same parent view. You need to create a new view or inflate a new view every time.

like image 37
mmathieum Avatar answered Nov 01 '22 17:11

mmathieum