整体思路:
1.添加控件ViewPager
2.创建fragment--BlankFragment
3.在BlankFragment的java文件内创建静态方法newInstance(int id),返回值为Fragment
Bundle bundle=new Bundle();
bundle.putInt("id",id);
BlankFragment fragment=new BlankFragment();
fragment.setArguments(bundle);
return fragment;
4.在BlankFragment的onCreateView方法中,根据Bundle的数据,设置控件的内容
View view= inflater.inflate(R.layout.fragment_blank, container, false);
Bundle bundle=getArguments();
int id=bundle.getInt("id");
TextView textView=view.findViewById(R.id.txt_fragment);
textView.setText(MainActivity.name[id]);
return view;
name为自己设置的一个数组,实际上可以根据id,从数据库中获得所需数据
5.自定义PaperAdapter
public class MyPagerAdapter extends FragmentPagerAdapter{
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
//通过BlankFragment自定义的方法,根据位置,返回fragment
@Override
public Fragment getItem(int position) {
return BlankFragment.newInstance(position);
}
@Override
public int getCount() {
return mFragmentCount;
}
}
6.ViewPager加载Adapter
mFragmentCount=5;
name=new String[]{"one","two","three","four","five"};
ViewPager viewPager=findViewById(R.id.pager);
MyPagerAdapter adapter=new MyPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(adapter);
这样就OK了,下面就是效果图