[英]FragmentStatePageAdapter cache, how do I reference old fragments after activity recreated? (for ex - landscape mode)
In my app I got a ViewPager which is showing 3 fragments in a swipe views layout. 在我的应用程序中,我有一个ViewPager,它以滑动视图的布局显示3个片段。 If the activity is recreated (for example, if I go to landscape mode) I can't get a reference to the fragments anymore.
如果重新创建了活动(例如,如果我进入横向模式),则无法再获得对片段的引用。
This is my Adapter 这是我的适配器
public class TabsPagerAdapter extends FragmentStatePagerAdapter{
public static final String FRAGMENT_MAP = "fragmentMap";
private SparseArray<MyFragment> myFragmentMap = new SparseArray<MyFragment>();
public TabsPagerAdapter(FragmentManager fm){
super(fm);
}
@Override
public Fragment getItem(int arg0) {
MyFragment fragment = new MyFragment();
Bundle args = new Bundle();
String nameOfTab = actionBar.getTabAt(arg0).getText().toString();
ArrayList<VideoBookmark> listOfFragment = myBookmarkManager.getList(nameOfTab);
args.putParcelableArrayList(MyFragment.ARG_LIST, listOfFragment);
fragment.setArguments(args);
myFragmentMap.put(arg0, fragment);
return fragment;
}
@Override
//return mytabs.size()???
public int getCount() {
return NUM_OF_TABS;
}
public void destroyItem (ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
myFragmentMap.remove(position);
}
public Fragment getFragment(int key) {
return myFragmentMap.get(key);
}
public SparseArray<MyFragment> getFragmentMap(){
return myFragmentMap;
}
public void setNewFragmentMap(SparseArray<MyFragment> newMap){
myFragmentMap = newMap;
}
}
I get null pointer exception in this line 我在这一行中得到空指针异常
//get current fragment
int index = myViewPager.getCurrentItem();
Fragment fragment = myTabsPagerAdapter.getFragment(index);
EditText title = (EditText) fragment.getView().findViewById(R.id.new_title);
I checked, this is happening because the getItem method is not called, so I guess the adapter reuses old fragments in some way, but how can I access this fragments cache to get my old fragments and to be able to use the findViewById method? 我检查了一下,这是因为未调用getItem方法而发生的,所以我猜适配器会以某种方式重用旧片段,但是如何访问此片段缓存以获取旧片段并能够使用findViewById方法? Thank you!
谢谢!
getFragmentManager.findFragmentByTag()// <<-如果要动态管理片段getFragmentManager.findFragmentById()// <<-如果在布局文件中使用<fragment>。
I'm still not sure of this, but I solved calling instantiateItem(viewpager, position)
to get the fragment at the given position. 我仍然不确定,但是我解决了调用
instantiateItem(viewpager, position)
来获取给定位置的片段。 If I got it right this method returns the fragment at the given position if it exists, if not it creates another one (I'm guessing it calls getItem()
) 如果我做对了,则此方法返回给定位置处的片段(如果存在),如果不存在,它将创建另一个片段(我猜它调用
getItem()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.