本來我得到這個錯誤:在衝突的Android錯誤消息:指定的孩子已經有一個家長。你必須調用removeView()對兒童的父母第一
customSection.addView(customLayout);
The specified child already has a parent. You must call removeView() on the child's parent first
所以我添加
((LinearLayout)customLayout.getParent()).removeView(customLayout);
現在得到
java.lang.NullPointerException
因此,如果孩子有父母,並且我必須先從父母中刪除孩子,爲什麼getParent()返回null?
我有一個抽象片段,它允許派生類爲列表適配器提供自定義佈局。相關代碼:
綁定:
public void bind(DataObject row) {
View customLayout = getChildItemView(row);
if (customLayout != null) {
((LinearLayout) customLayout.getParent()).removeView(customLayout);
customSection.removeAllViews();
customSection.addView(customLayout);
customSection.setVisibility(View.VISIBLE);
} else {
customLayout.setVisibility(View.INVISIBLE);
}
}
protected View getChildItemView(CommonRow row) {
if (parentView == null) {
parentView = (LinearLayout) LayoutInflater.from(getActivity())
.inflate(R.layout.list_item_custom_section,
new LinearLayout(getActivity()), true);
label = (TextView) parentView.findViewById(R.id.txtData1Label);
value = (TextView) parentView.findViewById(R.id.txtData1Value);
}
label.setText("Minimum");
value.setText(manager.formatMoney(((SpecificDataRow) row).minimum));
return parentView;
}
我也試過inflater.inflate(R.layout.list_item_custom_section, null)
......假,空/假的,怎麼辦?
編輯:
@allprog,我知道一些清理是必要的。我在一天結束的時候寫了這篇文章,有點匆忙。自從清理了代碼之後,我分離出了視圖的綁定和擴展。清理代碼:
private class ViewHolder {
....
public ViewHolder(View v) {
Butterknife.inject(this, v);
View custom = createCustomView(customSection);
if (custom != null) {
customSection.setVisibility(View.VISIBLE);
customSection.addView(custom);
}
}
public void bind(CommonRow row) {
......
bindCustomView(row, customSection);
}
}
子類:
@Override
protected View createCustomView(ViewGroup parent) {
return LayoutInflater.from(getActivity()).inflate(R.layout.list_item_custom_section, parent, false);
}
@Override
protected void bindCustomView(CommonRow row, ViewGroup section) {
TextView label = Views.findById(section, R.id.txtData1Label);
TextView value = Views.findById(section, R.id.txtData1Value);
label.setText("Minimum");
value.setText(manager.formatMoney(((SpecificRow) row).minimum));
}
suitianshi了它第一,我原來的[蓬頭垢面]代碼,這是解決方案。
什麼是'customSection'?你能在第一次初始化的地方顯示代碼嗎? –
它在getChildItemView(CommonRow row)方法中。 parentView =(LinearLayout)LayoutInflater.from(getActivity())。inflate(R.layout.list_item_custom_section,new LinearLayout(getActivity()),true); – Jack
你可以發佈list_item_custom_section的XML嗎?我懷疑你正在嘗試添加視圖到自己。另外,變量'customSection'仍然需要在某處聲明(並設置)。你可以發佈該代碼嗎? –