1. 程式人生 > >TabLayout+ViewPager

TabLayout+ViewPager

package com.example.day20.Fragment;

import android.os.Bundle; import android.support.annotation.Nullable; import android.support.design.widget.TabLayout; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentPagerAdapter; import android.support.v4.view.ViewPager; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup;

import com.example.day20.R;

import java.util.ArrayList; import java.util.List;

/**

  • A simple {@link Fragment} subclass. */ public class Fragment02 extends Fragment {

    private TabLayout tab; private ViewPager pager; private ArrayList list; private ArrayList title;

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = View.inflate(getActivity(), R.layout.fragment02, null); tab = view.findViewById(R.id.tab); pager = view.findViewById(R.id.pager); list=new ArrayList<>(); title=new ArrayList<>(); title.add(“廢材”); title.add(“垃圾”); title.add(“樂色”); title.add(“牲口”); for (int i=0;i<4;i++){ list.add(new Fragment03()); tab.addTab(tab.newTab().setText(title.get(i))); } pager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) { @Override public Fragment getItem(int position) { return list.get(position); }

         @Override
         public int getCount() {
             return list.size();
         }
    
         @Nullable
         @Override
         public CharSequence getPageTitle(int position) {
             return title.get(position);
         }
     });
     tab.setupWithViewPager(pager);
     return view;
    

    }

}