Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

retain state of viewpager fragments android

I have a viewpager in a fragment in which i am showing 3 fragments but when I open the fragment first time it opens fine and when I move to another fragment and came back to the viewpager fragment it doesn't show the fragments in view pager then I have to either change the orientation of the phone or keep swiping the viewpager for the hidden fragments to show.

I have googled it and now I know I have to set the tag to each fragment and retrieve fragment with findfragmentbytag method but problem is when I try to set the tag to fragment

getSupportFragmentManager().beginTransaction().add(myFragment, "Some Tag").commit();

above line crashes my app and logcat shows "cant set tag to fragment", I know I'm doing some stupid mistake

this is the complete code of my fragment. I would really appreciate if one could guide me where to write the code for setting the tag of fragments. thanks in advance.

public class MatchesListingFragment extends Fragment implements ActionBar.TabListener {

    Context context;
    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;
    ActionBar actionBar;
    Matchlistings db;
    Bundle savedInstanceState;

    Fragment livescore,fixture,results;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        this.savedInstanceState = savedInstanceState;
        db = new Matchlistings(getActivity());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_matches, container, false);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity().getApplicationContext();

        if(savedInstanceState == null){
            livescore = new LiveScoreListingFragment();
            fixture = new FixturesListingFragment();
            results = new ResultsListingFragment();
        }

        if(!Constants.is_listing_refreshed){
            Log.i(MainActivity.TAG,"refreshing list");
            db.loadListingsFromServer().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
        }

        actionBar = getActivity().getActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        if(mSectionsPagerAdapter == null)
        mSectionsPagerAdapter = new SectionsPagerAdapter(getActivity().getSupportFragmentManager());
        mViewPager = (ViewPager) getView().findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });


        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            Tab tb = actionBar.newTab()
            .setText(mSectionsPagerAdapter.getPageTitle(i))
            .setTabListener(this);

            actionBar.addTab(tb);

        }
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        Fragment fragment;

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            switch(position){
            case 0:

                fragment = livescore;
                return fragment;
            case 1:
                fragment = fixture;
                return fragment;
            case 2:
                fragment = results;
                return fragment;
            case 3:
                fragment = new LiveScoreListingFragment();
                return fragment;
            }
            return null;
        }

        @Override
        public int getCount() {
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            switch (position) {
            case 0:
                return "LIVE";
            case 1:
                return "FIXTURES";
            case 2:
                return "RESULTS";
            case 3:
                return "HOT";
            }
            return null;
        }
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        actionBar.removeAllTabs();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    }

    @Override
    public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabSelected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
        // TODO Auto-generated method stub

    }

}

enter image description here

EDIT: i have now tried to get the fragment from viewpager by tag instead of creating new fragment everytime. but problem is still same.

FixturesListingFragment fixture = (FixturesListingFragment) getActivity().getSupportFragmentManager().findFragmentByTag("android:switcher:"+R.id.pager+":1");
                if(fixture == null)
                    fixture = new FixturesListingFragment();
like image 714
Wasif Khalil Avatar asked Jan 30 '14 08:01

Wasif Khalil


2 Answers

Have you tried to use setOffscreenPageLimit? if you have 3 pages then set it to 2. This way pages won't be recreated even if the app is on iddle state. Here is the link

like image 82
Angmar Avatar answered Oct 06 '22 02:10

Angmar


I Have solved thiw problem by just using setOffScreenpageLimit(int) to the number of additional tabs that I have.

private void setupViewPager(ViewPager viewPager) {
    ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
    adapter.addFragment(new FragmentHome(), "Home");
    adapter.addFragment(new FragmentEProfile(), "e-Profile");
    adapter.addFragment(new FragmentResults(), "Results");
    adapter.addFragment(new FragmentOutpass(), "Outpass");
    viewPager.setAdapter(adapter);
    viewPager.setOffscreenPageLimit(3);
}
like image 28
Sandeep Samudrala Avatar answered Oct 06 '22 04:10

Sandeep Samudrala