getActivity() 在 Fragment 函数中返回 null [英] getActivity() returns null in Fragment function
问题描述
我有一个带有这样的公共方法的片段(F1)
I have a fragment (F1) with a public method like this
public void asd() {
if (getActivity() == null) {
Log.d("yes","it is null");
}
}
是的,当我调用它时(从活动中),它是空的...
and yes when I call it (from the Activity), it is null...
FragmentTransaction transaction1 = getSupportFragmentManager().beginTransaction();
F1 f1 = new F1();
transaction1.replace(R.id.upperPart, f1);
transaction1.commit();
f1.asd();
一定是我做错了什么,但我不知道那是什么.
It must be something that I am doing very wrong, but I don't know what that is.
推荐答案
commit
安排事务,即它不会立即发生,而是安排在主线程下一次主线程上的工作线程准备好了.
commit
schedules the transaction, i.e. it doesn't happen straightaway but is scheduled as work on the main thread the next time the main thread is ready.
我建议添加一个
onAttach(Activity activity)
Fragment
的方法,并在其上放置一个断点,并查看相对于您对 asd()
的调用何时调用它.您会看到它在调用 asd()
的方法退出后被调用.onAttach
调用是 Fragment
附加到其活动的地方,从这一点开始 getActivity()
将返回非空(注意也有onDetach()
调用).
method to your Fragment
and putting a break point on it and seeing when it is called relative to your call to asd()
. You'll see that it is called after the method where you make the call to asd()
exits. The onAttach
call is where the Fragment
is attached to its activity and from this point getActivity()
will return non-null (nb there is also an onDetach()
call).
这篇关于getActivity() 在 Fragment 函数中返回 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!