1. 程式人生 > >Tablayout顯示導航欄

Tablayout顯示導航欄

1.首先,只要在build.gradle中加入compile ‘com.android.support:design:22.2.0’即可。

2.佈局檔案

<android.support.design.widget.TabLayout
    android:id="@+id/tablayout"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMode="scrollable"<!-- 加上這句話,代表tab數量大於螢幕寬度時,能實現水平滾動-->
    tabIndicatorColor="@android:color/transparent"
> <android.support.v4.view.ViewPager android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" android:id="@+id/pager"></android.support.v4.view.ViewPager>

3.activity介面程式碼

//存放資料的集合(網路請求的資料),也就是請求介面返回的導航欄的資訊裝到集合中
 private  List<String> li=new
ArrayList<>(); //存放fragment的集合 private List<Fragment> fragments = new ArrayList<Fragment(); //初始化view private void initView() { pager = (ViewPager) getView().findViewById(R.id.pager); tablayout = (TabLayout) getView().findViewById(R.id.tablayout); } //通過介面回撥得到網路請求的資料
@Override public void callBackhome(Object o) { newsBean news= (newsBean) o; for (int i = 0; i < news.getResult().getDate().size(); i++) { //遍歷集合拿到title li.add(news.getResult().getDate().get(i).getTitle()); //迴圈建立fragment MyFragment frag=new MyFragment(news.getResult().getDate().get(i).getUri()); fragments.add(frag); } FragmentAdapter adapter=new FragmentAdapter(fragments,li,getActivity().getSupportFragmentMan ager()); pager.setAdapter(adapter); //關聯 tablayout.setupWithViewPager(pager); tablayout.setTabTextColors(Color.BLACK,Color.RED); }

介面卡

 public class FragmentAdapter extends FragmentPagerAdapter { 
     private List<String> list=new ArrayList<>();   
     private List<Fragment> fragments;  

     public FragmentAdapter(List<Fragment> fragments,List<String> list, FragmentManager fm) {      
     super(fm);      
     this.fragments = fragments;   
     this.list=list;  
  }   
  @Override   
   public Fragment getItem(int position) {      
   return fragments.get(position);    
}
    @Override    

   public int getCount() {    

    return list.size();   
 } 

   @Override 
   public CharSequence getPageTitle(int position) { 
       return list.get(position);   
 }
}