本文主要是介绍ViewPager+Fragment出现的问题,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
Ps:很久之前解决的,今天回顾起来发现有点陌生,看来写到博客经常看到比较好吧.
之前做过个首界面是Viewpage+Fragment的,用的时候发现有一些瑕疵,一些情况下Fragment会给销毁,认真看了下Viewpager发现这个控件只会保存相邻两个Fragment,其他的则会销毁掉,导致我的Fragment一直新建,解决方法是:
public class adapter extends FragmentPagerAdapter {public FragmentManager fm;public mainAdapter(FragmentManager fm) {super(fm);this.fm = fm;}@Overridepublic Fragment getItem(int arg0) {return mFragmentList.get(arg0);}@Overridepublic int getCount() {return mFragmentList.size();}// 初始化时,去FragmentManager中取@Overridepublic Object instantiateItem(ViewGroup arg0, int arg1) {Fragment fragment = (Fragment) super.instantiateItem(arg0, arg1);fm.beginTransaction().show(fragment).commit();return fragment;// return super.instantiateItem(arg0, arg1);}// 销毁时时,FragmentManager保存起来@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {System.out.println("position Destory" + position);// super.destroyItem(container, position, object);Fragment fragment = mFragmentList.get(position);fm.beginTransaction().hide(fragment).commit();}}
之后又做个ViewPager+ViewPager其中第一个填充的是View,另外个是Fragment,发现事件的不会冲突(用View填充会出问题),看来Fragment很适合用ViewPager,
private class childAdapter extends PagerAdapter {private List<View> listAdapter;public Adapter(List<View> listAdapter) {this.listAdapter = listAdapter;}@Overridepublic int getCount() {return listAdapter.size();}@Overridepublic void destroyItem(ViewGroup container, int position, Object object) {((ChildViewPager) container).removeView(listAdapter.get(position));}@Overridepublic Object instantiateItem(ViewGroup container, int position) {((ChildViewPager) container).addView(listAdapter.get(position));return listAdapter.get(position);}@Overridepublic boolean isViewFromObject(View arg0, Object arg1) {return arg0 == arg1;}@Overridepublic int getItemPosition(Object object) {return super.getItemPosition(object);}}
这篇关于ViewPager+Fragment出现的问题的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!