public class MyFragmentFuYong extends Fragment implements View.OnClickListener {
//new 出本类对象,通过Bundle传值 最后返回一个myFragmentFuYong本类对象
//注意这个方法是静态的 为了让别的类可以调用到
//复用
public static Fragment getFuYong(String string) {
MyFragmentFuYong myFragmentFuYong = new MyFragmentFuYong();
Bundle bundle = new Bundle();
bundle.putString("string", string);
myFragmentFuYong.setArguments(bundle);
return myFragmentFuYong;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle arguments = getArguments();
if (arguments != null) {
name = arguments.getString("string");
}
}
//那么到现在这个string都是空的,到底怎么给string赋值呢,别着急,一步步来
List mFragmentList=new ArrayList<>();
List mList=new ArrayList<>();
TabLayout mTab = view.findViewById(R.id.mTab);
ViewPager mViewPager = view.findViewById(R.id.mViewPager);
mList.add("页面一");
mList.add("页面二");
mList.add("页面三");
mList.add("页面四");
mList.add("页面五");
//调用静态的MyFragmentFuYong.getFuYong()方法,for循环添加集合里的string数据
for (int i = 0; i < mList.size(); i++) {
//返回一个对象
Fragment fuYong = MyFragmentFuYong.getFuYong(mList.get(i));
//fragment集合添加这个对象,fragment集合就添加了5个fragment
mFragmentList.add(fuYong);
}
//然后是ViewPager适配器,搭配上TabLayout
FragmentApader apader = new FragmentApader(getChildFragmentManager(), mFragmentList, mList);
mViewPager.setAdapter(apader);
mTab.setupWithViewPager(mViewPager);
//顺便写上这个ViewPager适配器吧
public class FragmentApader extends FragmentPagerAdapter{
private ListmFragmentList;
private List mList;
public FragmentApader(FragmentManager fm, List mFragmentList, List mList) {
super(fm);
this.mFragmentList = mFragmentList;
this.mList = mList;
}
@Override
public Fragment getItem(int position) {
return mFragmentList.get(position);
}
@Override
public int getCount() {
return mFragmentList.size();
}
@Nullable
@Override
public CharSequence getPageTitle(int position) {
return mList.get(position);
}
}
//-------------------------------fragment的复用完成,如果想每个复用的页面返回不同的布局效果,可以加判断,在onCreateView里,通过name就行
//------------------------------这样判断
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
//先设置inflate 为空,再从下面赋值
View inflate = null;
//页面一
if (name.equals("页面一")) {
inflate = inflater.inflate(R.layout.keyilayout, null);
initViewssss(inflate);
}
//页面二
if (name.equals("页面二")) {
inflate = inflater.inflate(R.layout.keerlayout, null);
initViewss(inflate);
}
//页面三
if (name.equals("页面三")) {
inflate = inflater.inflate(R.layout.kesanlayout, null);
initViewsss(inflate);
}
//页面四
if (name.equals("页面四")) {
inflate = inflater.inflate(R.layout.kesilayout, null);
initView4(inflate);
}
//页面五
if (name.equals("页面五")) {
inflate = inflater.inflate(R.layout.nazhenglayout, null);
initView(inflate);
}
//最后统一返回一个inflate
return inflate;
}
//-----------------------------------------------------------------------------完-------------------------------------------------------------------------------