package duanxinmeng.bwie.com.sanzhoukao; 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 java.util.ArrayList; import java.util.List; /** * Created by Administrator on 2017/10/23/023. */ public class Fragment_Sy extends Fragment { private TabLayout tabLayout; private ViewPager viewPager; private List<String> list; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_sy,container,false); tabLayout = (TabLayout) view.findViewById(R.id.tab_layout); viewPager = (ViewPager) view.findViewById(R.id.pager); return view; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); list = new ArrayList<>(); list.add("推荐"); list.add("课程"); list.add("实践"); list.add("职业路径"); viewPager.setAdapter(new FragmentPagerAdapter(getChildFragmentManager()) { @Override public CharSequence getPageTitle(int position) { return list.get(position); } @Override public Fragment getItem(int position) { Fragment fragment = null; switch (position){ case 0: fragment = new Fragment_Tj(); break; case 1: fragment = new Fragment_Kc(); break; case 2: fragment = new Fragment_Sj(); break; case 3: fragment = new Fragment_Zy(); break; } return fragment; } @Override public int getCount() { return list.size(); } }); //关联 tabLayout.setupWithViewPager(viewPager); } }
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:orientation="vertical" android:background="@drawable/ad" android:layout_height="match_parent"> <android.support.design.widget.TabLayout android:id="@+id/tab_layout" android:layout_width="match_parent" android:layout_height="50px" app:tabGravity="center" app:tabIndicatorColor="@color/colorAccent" app:tabMode="scrollable" app:tabSelectedTextColor="@color/colorPrimaryDark" app:tabTextColor="@color/colorPrimary" > </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/pager" android:layout_width="match_parent" android:layout_height="match_parent"></android.support.v4.view.ViewPager> </LinearLayout>