从ViewPager检索片段我用的是ViewPager连同一个FragmentStatePagerAdapter承载三个不同的片段:[碎片1][碎片2][碎片3]当我想Fragment1从ViewPager在FragmentActivity.有什么问题,我该如何解决?
4 回答
慕斯王
TA贡献1864条经验 获得超2个赞
instantiateItem()
destroyItem()
Fragment(State)PagerAdapter
:
public class MyPagerAdapter extends FragmentStatePagerAdapter { SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>(); public MyPagerAdapter(FragmentManager fm) { super(fm); } @Override public int getCount() { return ...; } @Override public Fragment getItem(int position) { return MyFragment.newInstance(...); } @Override public Object instantiateItem(ViewGroup container, int position) { Fragment fragment = (Fragment) super.instantiateItem(container, position); registeredFragments.put(position, fragment); return fragment; } @Override public void destroyItem(ViewGroup container, int position, Object object) { registeredFragments.remove(position); super.destroyItem(container, position, object); } public Fragment getRegisteredFragment(int position) { return registeredFragments.get(position); }}
getRegisteredFragment
Fragment
ViewPager
: adapater.getRegisteredFragment(viewPager.getCurrentItem())
null
.
繁花不似锦
TA贡献1851条经验 获得超4个赞
public class MyPagerAdapter extends FragmentPagerAdapter { private Fragment mCurrentFragment; public Fragment getCurrentFragment() { return mCurrentFragment; }//... @Override public void setPrimaryItem(ViewGroup container, int position, Object object) { if (getCurrentFragment() != object) { mCurrentFragment = ((Fragment) object); } super.setPrimaryItem(container, position, object); } }
添加回答
举报
0/150
提交
取消