ViewPager嵌套Fragment

ViewPager嵌套Fragmentide

  1. 新建4個Fragment;this

  2. 新建ViewPagerAdapter繼承FragmentPagerAdapter;
    public class ViewpagerAdapter extends FragmentPagerAdapter {code

    private ArrayList<Fragment> arrayList;
    
        public ViewpagerAdapter(@NonNull FragmentManager fm,ArrayList<Fragment> arrayList) {
            super(fm);
            this.arrayList=arrayList;
        }
    
        @NonNull
        @Override
        public Fragment getItem(int position) {
            return arrayList.get(position);
        }
    
        @Override
        public int getCount() {
            return arrayList.size();
        }
    }
  3. 在MainActivity中爲ViewPager綁定適配器;繼承

arrayList=new ArrayList<>();
       arrayList.add(new Fragment1());
       arrayList.add(new Fragment2());
       arrayList.add(new Fragment3());
       arrayList.add(new Fragment4());
       viewpagerAdapter= new ViewpagerAdapter(getSupportFragmentManager(),arrayList);
       viewpager.setAdapter(viewpagerAdapter);
相關文章
相關標籤/搜索