本文介绍了Android的碎片getActivity()= NULL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用的片段在我的应用程序。并采用getActivity()时,同时使用起来非常普遍的问题是NPE。我知道我们可以通过,如果 getActivity检查()!= NULL 每一次,或者检查是否片段 isAdded()

I'm using fragments in my application. And the very common problem while using them are the NPE when using getActivity(). I know we can solve it by checking if getActivity() != null every single time or checking if the fragment isAdded().

在我的班级我收到活动的背景下,在60多个地方之一。如果getActivity检查()不为空或者片段仍然加入到活动中的所有地方是使code丑陋的,更大的和非维护。是否有任何其他的方式来处理呢?它甚至有可能摧毁片段(并停止任何工作也一直在做,而被删除),当它被从活动中删除?

In one of my classes I'm getting activity's context in more than 60 places. Checking if getActivity()is not null or if the fragment is still added to the activity in all the places is making the code ugly,larger and non-maintainable. Is there any other way to handle this?Is it even possible to destroy the fragment(and stop any work it has been doing while being removed) when it is removed from the activity?

Also这是方式建议吗?

推荐答案

getActivity将reinitilized的方法 - onActivityCreated()

getActivity will be reinitilized in method - onActivityCreated().

所以,它的安全)(根据生命周期片段的) - 例如在ONSTART() - 在这种情况下它的将是永远不能为null - 不需要做无用的检查,像isAdded和getActivity != NULL。

So it's safer to call getActivity() right after onActivityCreated() (according to lifecycle of fragments http://developer.android.com/guide/components/fragments.html) - for example in onStart() - in that case it's WILL BE NEVER NULL - no need to do useless checks like isAdded and getActivity != null.

P.S。如果我们使用的解决方案:

P.S. If we use that solution:

@Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        mActivity = activity;
    }

mActivity将不能为null - 但后来在法onActivityCreated()getActivity()成为与mActivity不同。我的意见 - 当然,我们可以节省可变整个活动,但它的安全遵循Android的碎片生命周期的工作流程,并获得活动后onActivityCreated()右

mActivity will be never null - but later in method onActivityCreated() getActivity() became different with mActivity.My opinion - sure we can save whole activity in variable, but it's safer to follow android fragments lifecycle workflow and get activity right after onActivityCreated()

这篇关于Android的碎片getActivity()= NULL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-21 06:44