1. 程式人生 > >IllegalStateException: The specified child already has a parent問題解決辦法

IllegalStateException: The specified child already has a parent問題解決辦法

       我在使用DropDownMenu的時候將佈局檔案的recycleview傳進setDropDownMenu的方法裡面,出現了IllegalStateException :The specified child already has a parent. You must call removeView() 的錯誤。原來發現我的Activity的recycleview和我傳進方法裡面用到的view的parent是不一致的,所以需要我在activity裡面new一個recycleview。它的parent是不屬於activity的。貼出關鍵程式碼入選如下 :

 final RecyclerView mRecyclerViewDelivery =new RecyclerView(this);
        mRecyclerViewDelivery.setLayoutManager(new LinearLayoutManager(mcontext));
        mRecyclerViewDelivery.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.VERTICAL, 6, getResources().getColor(R.color.black)));
        mDeliveryPresenter = new DeliveryPresenter(mcontext);
        mDeliveryPresenter.initDeliveryList(mRecyclerViewDelivery);
        mRecyclerViewDelivery.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
public void setDropDownMenu(@NonNull List<String> tabTexts, @NonNull List<View> popupViews, @NonNull View contentView) { if (tabTexts.size() != popupViews.size()) { throw new IllegalArgumentException("params not match, tabTexts.size() should be equal popupViews.size()"); } for (int i = 0; i < tabTexts.size(); i++) { addTab(tabTexts, i); } if (containerView.getChildAt(0) != null){ containerView.removeViewAt(0); } containerView.addView(contentView, 0); maskView = new View(getContext()); maskView.setLayoutParams(new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT)); maskView.setBackgroundColor(maskColor); maskView.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { closeMenu(); } }); if (containerView.getChildAt(1) != null){ containerView.removeViewAt(1); } containerView.addView(maskView, 1); maskView.setVisibility(GONE); if (containerView.getChildAt(2) != null){ containerView.removeViewAt(2); } popupMenuViews = new FrameLayout(getContext()); popupMenuViews.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, (int) (DeviceUtils.getScreenSize(getContext()).y*menuHeighPercent))); popupMenuViews.setVisibility(GONE); containerView.addView(popupMenuViews, 2); for (int i = 0; i < popupViews.size(); i++) { popupViews.get(i).setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)); popupMenuViews.addView(popupViews.get(i), i); } }

dropDownMenu.setDropDownMenu(Arrays.asList(headers), popupViews, mRecyclerViewDelivery);