ViewPager+RadioGroup+Fragment仿微信實現底部導航功能
阿新 • • 發佈:2019-02-15
public class ContentFragment extends BaseFragment { private View view; private RadioGroup radio_group; private ViewPager vp; private ArrayList<BasePager> list; @Override public View initView() { view = View.inflate(activity, R.layout.frame_content, null); radio_group = (RadioGroup) view.findViewById(R.id.radio_group); vp = (ViewPager) view.findViewById(R.id.vp); return view; } @SuppressWarnings("deprecation") @Override public void initData() { list = new ArrayList<BasePager>(); list.add(new FirstFragment(activity)); list.add(new SecondFragment(activity)); list.add(new ThirdFragment(activity)); list.add(new fourthlyFragment(activity)); list.add(new fifithFragment(activity)); radio_group.setOnCheckedChangeListener(new OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, int checkedId) { switch (checkedId) { case R.id.rb1: vp.setCurrentItem(0); break; case R.id.rb2: vp.setCurrentItem(1); break; case R.id.rb3: vp.setCurrentItem(2); break; case R.id.rb4: vp.setCurrentItem(3); break; case R.id.rb5: vp.setCurrentItem(4); break; } } }); vp.setAdapter(new PagerAdapter() { @Override public boolean isViewFromObject(View arg0, Object arg1) { return arg0 == arg1; } @Override public int getCount() { return list.size(); } @Override public Object instantiateItem(ViewGroup container, int position) { /* * 郜哥,這個地方下邊寫的假資料,只是作為一個demo * * 這個地方可以通過儲存fragment的集合,取出fragment,返回fragment中的view物件, * 但是呢,想點選一個radio_button,返回一個相對應的view,就得寫一個list集合中五個fragment的父類 * 在父類中也定義一個initview()方法,返回每個繼承這個父類的fragment的view物件,然後在這裡如下寫: * * container.addView(list.get(position).rootView); * rootview就是父類中的在initview()中返回的view * * * 上邊的list集合裡面的資料都沒用到 */ container.addView(list.get(position).rootview); return list.get(position).rootview; } @Override public void destroyItem(ViewGroup container, int position, Object object) { container.removeView((View) object); } }); vp.setCurrentItem(0); radio_group.check(R.id.rb1); vp.setOnPageChangeListener(new OnPageChangeListener() { @Override public void onPageSelected(int position) { // 噹噹前的viewpager狀態改變的時候的時候,radiogroup也切換 int currentItem = vp.getCurrentItem(); System.out.println("currentItem==="+currentItem); switch (currentItem) { case 0: radio_group.check(R.id.rb1); break; case 1: radio_group.check(R.id.rb2); break; case 2: radio_group.check(R.id.rb3); break; case 3: radio_group.check(R.id.rb4); break; case 4: radio_group.check(R.id.rb5); break; } } @Override public void onPageScrolled(int arg0, float arg1, int arg2) { } @Override public void onPageScrollStateChanged(int arg0) { } }); } }