TabLayout的使用


第一步首先利用第三方的design中的tablayout

布局文件

<android.support.design.widget.TabLayout
    android:id="@+id/tab"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabGravity="center"
    app:tabSelectedTextColor="#cc0000"
    app:tabTextColor="#000000"
    app:tabMode="scrollable"
    />
tabGravity居中显示
tabTextColor 不点击时字体的颜色
tabSelectedTextColor 点击时字体颜色
tabMode 可滑动


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


搭配viewpager使用 实现滑动的效果;
 
  
List fragments=new ArrayList<>();  

fragments.add(new Fragment1());
fragments.add(new Fragment2());
fragments.add(new Fragment3());
fragments.add(new Fragment4());
fragments.add(new Fragment5());
fragments.add(new Fragment6());
fragments.add(new Fragment7());
fragments.add(new Fragment8());
fragments.add(new Fragment9());
fragments.add(new Fragment10());
//将tablayout和viewpager绑定
tab.setupWithViewPager(vp)
 
 
  
//给viewpager设置适配器

adapter = new MyAdapter(getSupportFragmentManager(),this,fragments);
vp.setAdapter(adapter);


//自定义适配器类
public class MyAdapter extends FragmentPagerAdapter {
    private Context context;
    private List list;
    private String[] title={"社会","国内","国际","娱乐","社会","国内","国际","娱乐","国际","娱乐"};
    public MyAdapter(FragmentManager fm, Context context, List list) {
        super(fm);
        this.context = context;
        this.list = list;
    }

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


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

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


//重写方法实现tablayout和viewpager联动
    @Override
    public CharSequence getPageTitle(int position) {
        return title[position];
    }
}






你可能感兴趣的:(TabLayout的使用)