TabLayout的使用

原创
2017/02/25 20:24
阅读数 20

TabLayout和ViewPager + Fragment + FragmentPagerAdapter联合使用

<!--tab标签-->
<android.support.design.widget.TabLayout
    android:id="@+id/tabLayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabIndicatorColor="#d722e9"
    app:tabIndicatorHeight="2dp"
    app:tabTextColor="#f00"
    app:tabSelectedTextColor="#999"
    ></android.support.design.widget.TabLayout>

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


public class MainActivity extends AppCompatActivity {

    private List<Fragment> fragments;

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

        //初始化控件
        TabLayout tabLayout = (TabLayout) findViewById(R.id.tabLayout);
        ViewPager vp = (ViewPager) findViewById(R.id.vp);

        fragments = new ArrayList<>();
        fragments.add(setTitile(new Tab1Fragment(),"tab1"));
        fragments.add(setTitile(new Tab2Fragment(),"tab2"));
        fragments.add(setTitile(new Tab3Fragment(),"tab3"));

        vp.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));

        tabLayout.setupWithViewPager(vp);
    }

    private Fragment setTitile(Fragment fragment,String title){
        Bundle args = new Bundle();
        args.putString("title",title);
        fragment.setArguments(args);
        return fragment;
    }

    private class MyPagerAdapter extends FragmentPagerAdapter{

        public MyPagerAdapter(FragmentManager fm) {
            super(fm);
        }

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

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

        @Override
        public CharSequence getPageTitle(int position) {
            return fragments.get(position).getArguments().getString("title");
        }
    }
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部