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

后端 未结 8 1591
半阙折子戏
半阙折子戏 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<View> 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<View>(rootView);
           }
      return rootView;
      }
    
    0 讨论(0)
  • 2020-12-04 18:48

    I have also faced this problem.

    You can solve it by just add single line mViewPager.setOffscreenPageLimit(3);

    public class SwipeyTabsSampleActivity extends FragmentActivity {
    
    ...
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        setContentView(R.layout.main);
    
        mViewPager = (ViewPager) findViewById(R.id.viewpager);
        mTabs = (SwipeyTabs) findViewById(R.id.swipeytabs);
    
        SwipeyTabsPagerAdapter adapter = new SwipeyTabsPagerAdapter(this,
                getSupportFragmentManager());
        mViewPager.setAdapter(adapter);
    
        mViewPager.setOffscreenPageLimit(3);  <------  Add this one
    }
    
    }
    

    Good Luck.

    0 讨论(0)
提交回复
热议问题