,我發現了以下錯誤:問題:addView與ArrayList的
java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
我從視圖中刪除父,但它不能正常工作。
代碼:
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 */
有什麼不對?
編輯
基於這樣一個問題:Dynamic layout inflator within a loop
你能解釋一下你在做什麼嗎? –
創建產品列表,使用哪種模型的XML佈局。此佈局的內容是一個包含2個文本和一個圖像的LinearLayout(將此擴展) –
如果您需要列表,爲什麼不使用ArrayAdapter? –