Fragment getView() always returning null for Fragments created by a FragmentStatePagerAdapter

前端 未结 1 414
隐瞒了意图╮
隐瞒了意图╮ 2021-02-06 02:40

I have been reading a lot about fragments. Have found other people having problems retrieving fragments view because null was always returned but no answer solved my problem. Wh

相关标签:
1条回答
  • 2021-02-06 03:23

    So I need to get the current fragment imageview but I can't because fragment.getView() always is null, the activity associated with the fragment is null too and I can't figure out why is it.

    That is happening because you're expecting _iva.getItem(index); to return the Fragment that the ViewPager uses for the page corresponding to the specified index. That will not happen as the ViewPager has already called the getItem method to get the fragments it needs and after your call the getItem method you get a new ImageViewURLFragment instance. This new instance isn't tied to the Activity(getActivity() returns null) and its view wasn't created.

    As you use a FragmentStatePagerAdapter try the code below to get the currently visible Fragment:

    if (item.getItemId()==R.id.saveToSD) {
         int index = _vp.getCurrentItem();
         Fragment fragment = _vp.getAdapter().instantiateItem(_vp, index);
         //...
    
    0 讨论(0)
提交回复
热议问题