android - Fragment getView() 总是返回null

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

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Android Fragment 中,`getActivity()` 方法返回 null 的情况通常发生在以下几种情况下: 1. 在 `onAttach()` 方法之前调用 `getActivity()`:`onAttach()` 是 Fragment 生命周期中的第一个调用方法,此时 Fragment 已经与 Activity 关联,但是 `getActivity()` 方法还没有返回有效的 Activity 对象。如果你在 `onAttach()` 之前尝试调用 `getActivity()`,它会返回 null。 2. 在 Fragment 的生命周期方法外部调用 `getActivity()`:Fragment 生命周期中的一些方法(如 `onCreateView()`、`onActivityCreated()`、`onStart()`、`onResume()` 等)之外的地方调用 `getActivity()` 方法,可能导致返回 null。这是因为这些方法在 Fragment 生命周期的不同阶段会被多次调用,只有在特定的生命周期阶段才能获取到有效的 Activity 对象。 3. 在 Fragment 被销毁后调用 `getActivity()`:如果在 Fragment 被销毁后(如 `onDestroy()` 方法被调用后)继续尝试调用 `getActivity()`,它会返回 null。这是因为 Fragment 已经与 Activity 解除关联,不能再获取到 Activity 对象。 为了避免 `getActivity()` 返回 null,你可以尝试以下几种方法: 1. 在合适的生命周期方法内调用 `getActivity()`:确保在合适的生命周期方法(如 `onCreateView()`、`onActivityCreated()`、`onStart()`、`onResume()` 等)内调用 `getActivity()`,以确保获取到有效的 Activity 对象。 2. 使用 `onAttach()` 方法中的 `context` 参数:在 `onAttach()` 方法中,可以通过 `context` 参数来获取有效的 Activity 对象。你可以将其保存为成员变量,以便在其他地方使用。 3. 使用 `getView().getContext()`:如果你在 Fragment 的视图已经创建之后需要获取有效的 Activity 对象,可以使用 `getView().getContext()` 方法来获取。 请根据你的具体情况选择适合的方法来获取有效的 Activity 对象,避免 `getActivity()` 返回 null
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值