Can't communicate with fragments in ViewPager after orientation change

129 views Asked by At

I have a tab that holds a view pager with 5 fragments in it.

When onPageSelected is called then I tell the current fragment to animate up using

((ItemFragment) pagerAdapter.getItem(position)).animateUp();

and Inside the fragment

public void animateUp(){
     if(linearLayout != null){
          linearLayout.animate().translationYBy(-75));
    } 
}

Everything seems to work fine until I rotate the device. The fragments are shown and I can move them but the animateUp() method doesn't do anything. It seems like the viewpager doesn't have a reference to the fragments being shown.

Edit: onCreate is empty, here is onCreateView

 public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_explore_tab, container, false);
    pager = (MultiViewPager)rootView.findViewById(R.id.pager);

    List<Fragment> fragmentsList = new ArrayList<>();
    for(int i = 0; i < header.length; i++){
        ItemFragment fragment = new ItemFragment();
        Bundle bundle = new Bundle();
        bundle.putInt(ItemFragment.IMAGE_KEY, header[i]);
        fragment.setArguments(bundle);
        fragmentsList.add(fragment);
    }

    pager.addOnPageChangeListener(new OnPageChangeListener() {

        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        }

        @Override
        public void onPageSelected(int position) {
            ((ItemFragment) pagerAdapter.getItem(position)).animateUp();
        }

        @Override
        public void onPageScrollStateChanged(int state) {
        }
    });

    pagerAdapter = new BaseFragmentPagerAdapter(getChildFragmentManager(), fragmentsList);
    pager.setAdapter(pagerAdapter);

    return rootView;
}
1

There are 1 answers

0
once2go On
if(linearLayout != null){ *your listener change to null when you rotate device*
          linearLayout.animate().translationYBy(-75)); }

You must subscribe listener once more. Try to do this in onResume