In my app I got a ViewPager which is showing 3 fragments in a swipe views layout. 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? 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. 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()
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.