Android FragmentStatePagerAdapter

后端 未结 5 1341
太阳男子
太阳男子 2021-02-01 18:02

I\'m working with a FragmentStatePagerAdapter using this example.

The MyAdapter class is implemented as follows:

public static class MyAdapter extends Fr         


        
5条回答
  •  南笙
    南笙 (楼主)
    2021-02-01 18:24

    I have implemented something similar to what you have. I extended the FragmentPagerAdapter class like so:

    public class ContactsFragmentPagerAdapter extends FragmentPagerAdapter {
        ActionBar mActionBar;
        private List mFragments;
    
        public ContactsFragmentPagerAdapter(FragmentManager fm, List fragments) {
            super(fm);
            mFragments = fragments;
        }
    
        @Override
        public int getCount() {
            return mFragments.size();
        }
    
        @Override
        public Fragment getItem(int position) {
            return mFragments.get(position);
        }
    
        public void setActionBar(ActionBar bar) {
            mActionBar = bar;
        }
    }
    

    Notice I have added an argument to the constructor to pass in the List of Fragment objects. This way the getItem() method of this class can return any class that extends Fragment or any of its subclasses and not just one specific class ArrayListFragment like you have done.

    In the Activity where I instantiate my subclass of FragmentPagerAdapter I have passed in the list of Fragment objects:

    Class the instantiates the FragmentPagerAdapter

    public final class ContactManager extends Activity {
        private ContactsFragmentPagerAdapter mAdapter;
        private ViewPager mPager;
        public ActionBar mActionBar;
    
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
            setContentView(R.layout.contact_manager);
    
            List fragments = new Vector();
            fragments.add(Fragment.instantiate(this, ContactsListFragment.class.getName()));
            fragments.add(Fragment.instantiate(this, GroupsListFragment.class.getName()));
            mAdapter = new ContactsFragmentPagerAdapter(this.getFragmentManager(), fragments);
    
            mPager = (ViewPager) findViewById(R.id.pager);
            mPager.setAdapter(mAdapter);
    
            mPager.setOnPageChangeListener(new OnPageChangeListener() {
                @Override
                public void onPageScrollStateChanged(int arg0) {}
    
                @Override
                public void onPageScrolled(int arg0, float arg1, int arg2) {}
    
                @Override
                public void onPageSelected(int arg0) {
                    mActionBar.getTabAt(arg0).select();
                }
            });
    
        }
    
    }
    

    By accessing the variable "fragments", you can access a previously created Fragment so that you can run methods of that Fragment.

提交回复
热议问题