美文网首页Android
android TabLayout+ViewPager配合使用

android TabLayout+ViewPager配合使用

作者: 神情自若 | 来源:发表于2018-01-23 11:51 被阅读16472次

1.在项目app下的Module中添加依赖

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

2.相应的布局文件

<android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white"/>
 <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0.5px"
        android:background="@color/line_color"
        ></LinearLayout>
<android.support.design.widget.TabLayout
        android:id="@+id/tablayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#FFFFFF"
        app:tabGravity="fill"
        app:tabIndicatorColor="@color/toolBarColor"
        app:tabMode="fixed"
        app:tabSelectedTextColor="@color/toolBarColor"
        app:tabTextColor="#000000"
        />        

3.构建adapter

public class MyPagerAdapter extends FragmentPagerAdapter {
    private Context context;
    private List<Fragment> fragmentList;
    private List<String> list_Title;
    public MyPagerAdapter(FragmentManager fm,Context context,List<Fragment> fragmentList,List<String> list_Title) {
        super(fm);
        this.context = context;
        this.fragmentList = fragmentList;
        this.list_Title = list_Title;
    }

    @Override
    public Fragment getItem(int position) {
        return fragmentList.get(position);
    }
    @Override
    public int getCount() {
        return list_Title.size();
    }
    /**
     * //此方法用来显示tab上的名字
     * @param position
     * @return
     */
    @Override
    public CharSequence getPageTitle(int position) {
        return list_Title.get(position);
    }

4.tablayout和ViewPager联动

 fragmentList = new ArrayList<>();
        list_Title = new ArrayList<>();
        fragmentList.add(new OneFragment());
        fragmentList.add(new TwoFragment());
        list_Title.add("one");
        list_Title.add("two");
        viewpager.setAdapter(new MyPagerAdapter(getSupportFragmentManager(),HelpCenterActivity.this,fragmentList,list_Title));
tablayout.setupWithViewPager(viewpager);//此方法就是让tablayout和ViewPager联动

效果图如下


这里写图片描述

详细代码已经贴出 经过以上步骤就顶部导航切换了

相关文章

网友评论

    本文标题:android TabLayout+ViewPager配合使用

    本文链接:https://www.haomeiwen.com/subject/avcsaxtx.html