addView List - The specified child has already a parent

0

I'm getting the error

  

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

even removing Parent from the View.

Follow the code:

LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
LinearLayout root = (LinearLayout) linha.findViewById(R.id.ingredientes_sel);
List views = new ArrayList();

View view = inflater.inflate(R.layout.item_obs_carrinho, null);
view.setLayoutParams(
        new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));

if (tipo == 2 || tipo == 3) { //add
    for (int i = 0; i < objetos_add.get(0).length; i++) {
        if (!objetos_add.get(0)[i].equals("")) {
            if (view.getParent() != null)
                ((ViewGroup) view.getParent()).removeView(view);
            TextView n = (TextView) view.findViewById(R.id.item_ingred_carrinho);
            n.setText(objetos_add.get(0)[i]);

            TextView qtd = (TextView) view.findViewById(R.id.quantidade);
            qtd.setText(objetos_add.get(1)[i]);

            views.add(view);
        }
    }
}
if (tipo == 1 || tipo == 3) { //rem
    for (int i = 0; i < objetos_rem.get(0).length; i++) {
        if (!objetos_rem.get(0)[i].equals("")) {
            if (view.getParent() != null)
                ((ViewGroup) view.getParent()).removeView(view);
            TextView n = (TextView) view.findViewById(R.id.item_ingred_carrinho);
            n.setText(objetos_rem.get(0)[i]);

            TextView qtd = (TextView) view.findViewById(R.id.quantidade);
            qtd.setText("");

            ImageView add = (ImageView) view.findViewById(R.id.add_ou_rem);
            add.setImageResource(android.R.drawable.ic_delete);

            views.add(view);
        }
    }
}

for (int i = 0; i < views.size(); i++)
    root.addView((View) views.get(i)); /* <---- ERRO  */

What's wrong?

I made this modification in the last loop but now it only displays the last element in the "views" list:

for (int i = 0; i < views.size(); i++) {
    ViewGroup paren = (ViewGroup) ((ViewGroup) views.get(i)).getParent();
    if (paren != null) {
        paren.removeView((View) views.get(i));
    }
    root.addView((View) views.get(i));
}
    
asked by anonymous 08.03.2017 / 19:20

0 answers