如果你在使用Fragment的时候,有时会遇到调用Fragment.getView()的时候,总是返回一个null值。
可能出现此问题的原因是,你在Activity中,调用adapter.getItem()来获取当前Fragment。
大概如下
int index= _viewPaper.getCurrentItem();
Fragment fragment=_myFragmentAdapter.getItem(index);
//这一步总是返回null值
View view= fragment.getView();
ImageView iv=(ImageView)view.findViewWithTag("imageView");
Bitmap bmp=iv.getDrawingCache();
这是因为,这个Adapter.getItem方法返回的是一个新的Fragment实例,并不是当前的Fragment。
原文解释如下:
That is happening because you‘re expecting _myFragmentAdapter.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.
解决方法,用如下代码来获取一个当前可见的Fragment:
int index = _viewPaper.getCurrentItem();
Fragment fragment = _viewPaper.getAdapter().instantiateItem(_viewPaper, index);
//...