Update data in ListFragment as part of ViewPager

后端 未结 10 1856
一整个雨季
一整个雨季 2020-11-22 07:55

I\'m using the v4 compatibility ViewPager in Android. My FragmentActivity has a bunch of data which is to be displayed in different ways on different pages in my ViewPager.

10条回答
  •  终归单人心
    2020-11-22 08:33

    I want to give my approach in case it can help anyone else:

    This is my pager adapter:

     public class CustomPagerAdapter extends FragmentStatePagerAdapter{
        private Fragment[] fragments;
    
        public CustomPagerAdapter(FragmentManager fm) {
            super(fm);
            fragments = new Fragment[]{
                    new FragmentA(),
                    new FragmentB()
            };
        }
    
        @Override
        public Fragment getItem(int arg0) {
            return fragments[arg0];
        }
    
        @Override
        public int getCount() {
            return fragments.length;
        }
    
    }
    

    In my activity I have:

    public class MainActivity {
            private ViewPager view_pager;
            private CustomPagerAdapter adapter;
    
    
            @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            adapter = new CustomPagerAdapter(getSupportFragmentManager());
            view_pager = (ViewPager) findViewById(R.id.pager);
            view_pager.setAdapter(adapter);
            view_pager.setOnPageChangeListener(this);
              ...
             }
    
    }
    

    Then to get the current fragment what I do is:

    int index = view_pager.getCurrentItem();
    Fragment currentFragment = adapter.getItem(index);
    

提交回复
热议问题