isved()与Android片段中的null!= getActivity()相同吗?

时间:2017-05-14 18:43:19

标签: android android-fragments android-activity

我想知道这两种方法是否会导致相同的结果,或者哪种方法比另一种更好。

if(isAdded()){
//do something with activity since fragment is currently added to its activity.
}

if(null != getActivity()){
//do something with activity. Its not null
}

1 个答案:

答案 0 :(得分:7)

出于以下两个原因,

isAdded()最好在几乎所有情况下使用:

    如果片段当前已添加到其中,则
  1. isAdded()将返回true 活动。 getActivity()只返回关联的活动。在大多数情况下,这将返回相同的布尔值,但最好是安全的

  2. 编写

  3. 的代码较少

    源代码:

    http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/app/Fragment.java/

    /**
     * Return the Activity this fragment is currently associated with.
     */
    final public Activity getActivity() {
        return mActivity;
    }
    
    /**
     * Return true if the fragment is currently added to its activity.
     */
    final public boolean isAdded() {
        return mActivity != null && mAdded;
    }