android - Fragment getView() 總是返回null

來源:互聯網
上載者:User

標籤:get   wpa   getc   strong   image   ant   under   oid   create   

如果你在使用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 Fragmentthat 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);

    //...

 

參考地址:http://stackoverflow.com/questions/14789519/fragment-getview-always-returning-null-for-fragments-created-by-a-fragmentstat

android - Fragment getView() 總是返回null

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.