//布局
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent"> <android.support.design.widget.TabLayout android:id="@+id/my_Tab" android:layout_width="match_parent" android:layout_height="wrap_content" app:tabGravity="center"> </android.support.design.widget.TabLayout> <android.support.v4.view.ViewPager android:id="@+id/vp" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_below="@+id/my_Tab"></android.support.v4.view.ViewPager> </RelativeLayout>
//activity
//fragment
public class ShowVpFragment extends Fragment { private TabLayout my_tab; private ViewPager view_pager; private List<DataType> list; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.show_frag, container, false); my_tab = v.findViewById(R.id.my_Tab); view_pager = v.findViewById(R.id.vp); initType(); /*for (int i = 0; i <5 ; i++) { my_tab.addTab(my_tab.newTab().setText(list.get(i).getmTitle())); }*/ view_pager.setAdapter(new MyVpAdapter(getChildFragmentManager())); my_tab.setupWithViewPager(view_pager); return v; } private void initType() { list = new ArrayList<>(); list.add(new DataType("数据新闻","数据新闻")); list.add(new DataType("快讯","快讯")); list.add(new DataType("头条","头条")); list.add(new DataType("精编公告","精编公告")); list.add(new DataType("社会","社会")); } class MyVpAdapter extends FragmentPagerAdapter{ public MyVpAdapter(FragmentManager fm) { super(fm); } @Override public CharSequence getPageTitle(int position) { return list.get(position).getmTitle(); } @Override public Fragment getItem(int position) { ContentFragment contentFragment = new ContentFragment(); Bundle bundle = new Bundle(); bundle.putString("type",list.get(position).getmType()); contentFragment.setArguments(bundle); return contentFragment; } @Override public int getCount() { return list.size(); } } }
//子fragment
public class ContentFragment extends Fragment { private TextView text; @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { View v = inflater.inflate(R.layout.content_frag, container, false); text = v.findViewById(R.id.ttv); return v; } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); Bundle arguments = getArguments(); String type = arguments.getString("type"); text.setText(type+"~~~~~"); } }