How to solve for viewpager : The specified child already has a parent. You must call removeView() on the child's parent first

后端 未结 8 1646
半阙折子戏
半阙折子戏 2020-12-04 18:05

Into my project I am using viewpager with three tabs named History,Main,Map.Main activity contain Timer,stopwatch,etc

8条回答
  •  悲哀的现实
    2020-12-04 18:43

    Here's my solution (used in each of the fragments) , which allows both smoothness and avoids memory problems:

    ...
    private LayoutInflater mInflater;
    private WeakReference mRootView = null;
    ...
    
    @Override
    public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) 
      {
      if (inflater != null)
        mInflater = inflater;
      else
        mInflater = LayoutInflater.from(getActivity());
      View rootView = mRootView == null ? null : mRootView.get();
      if (rootView != null) 
          {
          final ViewParent parent = rootView.getParent();
          if (parent != null && parent instanceof ViewGroup)
            ((ViewGroup) parent).removeView(rootView);  
          }
      else 
           {
           rootView = mInflater.inflate(R.layout.fragment_test, null, false);
           mRootView = new WeakReference(rootView);
           }
      return rootView;
      }
    

提交回复
热议问题