0

I'am stuck for about 2 hour in order to try to create a TableRow who was multiples infalted layouts in it.My code looks like this:

LayoutInflater inflater = LayoutInflater.from(this);
TableLayout tblLayout = inflater.inflate(R.layout.tblL,parent,false);
TableRow tableRow = (TableRow) tblListItems.findViewById(R.id.tableRow );
View headerCell = inflater.inflate(R.layout.header_col,tblListItems,false);
TextView tvCellName = (TextView) headerCell.findViewById(R.id.tvCellName);

    for(String item: items) {

        tvCellName.setText(item);

        tableRow.addView(tvCellName);
    }

relativeLayout2.addView(tblLayout);

The error I get :

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

What I'am doing wrong and how should I do it right ?

1 Answer 1

1

A view can only have one parent. You're trying to add the same view over and over again.

for(String item: items) {

    tvCellName.setText(item);

    tableRow.addView(tvCellName); // this will add the same view.
}

If you want to add another view you need to create the view dynamically, inside the for, and not inflate it, like:

tvCellName = new TextView(this);//this creates a new view, that doesn't have a parent.

edit

Inflate your views inside the for:

 View headerCell;
 TextView tvCellName;
 for(String item: items) {
        headerCell = inflater.inflate(R.layout.header_col,tblListItems,false);
        tvCellName = (TextView) headerCell.findViewById(R.id.tvCellName);
        tvCellName.setText(item);
        tableRow.addView(tvCellName);
    }
Sign up to request clarification or add additional context in comments.

3 Comments

The problem is that my TextView need to be from a layout that was inflated. TextView tvCellName = (TextView) headerCell.findViewById(R.id.tvCellName);
You need to create the view dynamically. Your problem is not that. Your problem is that a view CAN'T be added multiple times.
Sorry. The thing is that I don't need to add tvCellName to tableRow. I need to add headerCell which has a TextView in it on the table row.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.