Android之TabLayout+ViewPager+Fragment实现页面切换

一:添加design依赖

使用TabLayout需要添加design依赖:

implementation 'com.android.support:design:27.1.1'

二:创建Fragment

创建三个Fragment:Fragment1、Fragment2、Fragment3,分别导入页面布局fragment1、fragment2、fragment3:

public class Fragment1 extends Fragment {

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

}


    


三:创建MyFragmentPagerAdapter类继承自FragmentPagerAdapter类:

public class MyFragmentPagerAdapter extends FragmentPagerAdapter {

    private FragmentManager fragmentManager;
    private List fragmentList;
    private List title;

    public MyFragmentPagerAdapter(FragmentManager supportFragmentManager, List fragments,List titles) {
        super(supportFragmentManager);
        fragmentManager = supportFragmentManager;
        fragmentList = fragments;
        title = titles;

    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }

    @Override
    public int getCount() {
        return fragmentList.size();
    }

    @Override
    public CharSequence getPageTitle(int position){
        return title.get(position);
    }
}

四:在主页面布局中引入TabLayout和ViewPager:

    
    

        />

五:MainActivity代码:

public class MainActivity extends AppCompatActivity {

    TabLayout tabLayout;
    ViewPager viewPager;
    List titles;
    List fragments;
    Fragment fragment1;
    Fragment fragment2;
    Fragment fragment3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tabLayout = (TabLayout) findViewById(R.id.mytab);
        viewPager = (ViewPager) findViewById(R.id.myViewPager);

        titles = new ArrayList<>();
        titles.add("测试1");titles.add("测试2");titles.add("测试3");

        fragments = new ArrayList<>();
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();
        fragments.add(fragment1);
        fragments.add(fragment2);
        fragments.add(fragment3);

        MyFragmentPagerAdapter myFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager(),fragments,titles);

        viewPager.setAdapter(myFragmentPagerAdapter);

        tabLayout.setupWithViewPager(viewPager);
        
    }
}

效果如下:

Android之TabLayout+ViewPager+Fragment实现页面切换_第1张图片

你可能感兴趣的:(Android之控件)