仿今日头条APP页面切换

先展示效果

仿今日头条APP页面切换_第1张图片

下面状态栏切换就省略了,用的是Fragment切换,主要看上面切换
需要加的权限





1、先看布局


   
   
    

    
        

2、Java代码

public class Fragment01 extends Fragment {

    private TabLayout tabLayout;
    private ViewPager pager;
    private TabAdapter adapter;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment01,container,false);
        tabLayout = view.findViewById(R.id.tab);
        pager = view.findViewById(R.id.pager);

        String str[] = {"关注", "推荐", "热门", "美女", "汽车", "娱乐"};
        ArrayList list = new ArrayList<>();
        list.add(new Tab01());
        list.add(new Tab02());
        list.add(new Tab03());
        list.add(new Tab04());
        list.add(new Tab05());
        list.add(new Tab06());//每个Tab代表一个类 ,类里面找对应的XML布局
        
        //适配器
        adapter = new TabAdapter(getActivity().getSupportFragmentManager(), str, list);
        pager.setAdapter(adapter);
        tabLayout.setupWithViewPager(pager);
        return view;

    }
}

3、适配器代码

public class TabAdapter extends FragmentPagerAdapter {

    private String str[];
    private ArrayList list;

    public TabAdapter(FragmentManager fm, String[] str, ArrayList list) {
        super(fm);
        this.str = str;
        this.list = list;
    }
    @Override
    public Fragment getItem(int i) {
        return list.get(i);
    }

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

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

你可能感兴趣的:(开发)