標籤:
這個問題搞了我半天了,網上有很多人說需要找到該控制項的parent後,讓該parent 先remove需要添加的控制項,然後在添加,如:
if (view != null) { ViewGroup parent = (ViewGroup) view.getParent(); if (parent != null) { parent.removeView(view); }}try { view = inflater.inflate(R.layout.fragment_main, container, false);} catch (InflateException e) {}
也很多人說將inflater.inflate(R.layout.change_layout)改為 inflater.inflate(R.layout.change_layout, container, false);
但是我的情況是這樣的,有一個FragmentManager,控制4個Fragment,其中,3個Fragment是直接從layout檔案擷取,所以直接調用inflater.inflate(R.layout.change_layout, container, false);就可以,但是另一個Fragment是動態從我的自訂的View類載入,我一開始總是使用addView,不管我怎麼通過父類去remove,都報一樣的錯.
後來發現,在Fragment的onCreateView方法中,不用顯示addView方法,只要執行個體化一個View對象,即可(甚至不用返回該View對象).如
@Overridepublic View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {frameLayout = (FrameLayout) getActivity().findViewById(R.id.content);final String title = "最近一周AQI變化圖";data = new int[] { 1, 2, 3, 4, 5, 6, 7 };xLables = new String[] { "一", "二", "三", "四", "五", "六", "七" };view_brokenline = new BrokenLineView(frameLayout.getContext(), title,xLables, null, data);return null;}
Android-The specified child already has a parent. You must call removeView() on the child's parent first.