Android项目Tab类型主界面ViewPager+TabLayout+Fragment

效果图:

Tab.gif

代码:
布局




    
    

    
    

    
    

MainActivity

        //获取Tab名
        mTitles = getResources().getStringArray(R.array.main_titles);
        //viewPager设置适配器
        viewPager.setAdapter(new ViewPagerAdapter(getSupportFragmentManager(),mTitles));
        //关联viewpager
        tabLayout.setupWithViewPager(viewPager);

在res/values下创建arrays.xml



    
        首页
        应用
        游戏
        专题
        推荐
        分类
        热门
    

ViewPagerAdapter

/**
 * Created by 小阿远 on 2017/10/17.
 */

public class ViewPagerAdapter extends FragmentPagerAdapter{
    private static final int HOME_FRAGMENT = 0;
    private static final int APP_FRAGMENT = 1;
    private static final int GAME_FRAGMENT = 2;
    private static final int SPECIAL_FRAGMENT = 3;
    private static final int RECOMMEND_FRAGMENT = 4;
    private static final int CLASSIFY_FRAGMENT = 5;
    private static final int HOT_FRAGMENT = 6;

    private final String[] mtitles;
    public ViewPagerAdapter(FragmentManager fm,String[] titles) {
        super(fm);
        mtitles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position){
            case HOME_FRAGMENT:return new HomeFragment();

            case APP_FRAGMENT:return new APPFragment();

            case GAME_FRAGMENT:return new GameFragment();

            case SPECIAL_FRAGMENT:return new SubjectFragment();

            case RECOMMEND_FRAGMENT:return new RecommendFragment();

            case CLASSIFY_FRAGMENT:return new ClassifyFragment();

            case HOT_FRAGMENT:return new HotFragment();
        }
        return null;
    }

    @Override
    public int getCount() {
        return mtitles.length;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        return mtitles[position];
    }
}

你可能感兴趣的:(Android项目Tab类型主界面ViewPager+TabLayout+Fragment)