我想知道这两种方法是否会导致相同的结果,或者哪种方法比另一种更好。
if(isAdded()){
//do something with activity since fragment is currently added to its activity.
}
和
if(null != getActivity()){
//do something with activity. Its not null
}
答案 0 :(得分:7)
isAdded()
最好在几乎所有情况下使用:
isAdded()
将返回true
活动。 getActivity()
只返回关联的活动。在大多数情况下,这将返回相同的布尔值,但最好是安全的
编写
源代码:
/**
* 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;
}