Android Tablayout和viewpage fragment连用

依赖

compile 'com.android.support:design:23.4.0'

效果展示

这里写图片描述

布局

<android.support.design.widget.TabLayout
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:id="@+id/tablayout">
    </android.support.design.widget.TabLayout>

    <android.support.v4.view.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewpager">

viewpage适配器

public class FragmentAdapter extends FragmentPagerAdapter {

    private String [] title = {"one","two","three","four"};
    private List<Fragment> fragmentList;
    public FragmentAdapter(FragmentManager fm,List<Fragment> fragmentList) {
        super(fm);
        this.fragmentList = fragmentList;
    }
    @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[position];
    }
}

MainActivity

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

        ContentFragment fragment1 = new ContentFragment();
        ContentFragment fragment2 = new ContentFragment();
        ContentFragment fragment3 = new ContentFragment();
        ContentFragment fragment4 = new ContentFragment();
        fragments.add(fragment1);
        fragments.add(fragment2);
        fragments.add(fragment3);
        fragments.add(fragment4);
        adapter = new FragmentAdapter(getSupportFragmentManager(),fragments);
        viewpager.setAdapter(adapter);
        tablayout.setupWithViewPager(viewpager);
    }

最后一行是重点,切记切记!!

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页