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

为君一笑 提交于 2019-12-03 03:02:48

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);
     //...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!