getActivity()返回分段函数空 [英] getActivity() returns null in Fragment function

查看:158
本文介绍了getActivity()返回分段函数空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个片段(F1),像这样的公共方法

I have a fragment (F1) with public method like this

public void asd(){
if(getActivity()==null){Log.d("yes","it is null");}
}

是的,当我打电话(从活动),它是空...

and yes when I call(from the Activity) it 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 is that

推荐答案

提交调度交易,即不通俗易懂发生,但定为下次主线程准备在主线程的工作。

'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)

方法,你的片段,并把一个破发点上它,当它被称为相对于您的来电ASD()看。你会看到它,你拨打电话,以ASD()退出该方法后调用。该'onAttach'呼叫是其中所述片段被连接到它的活动,并从该点getActivity()将返回非空(NB也有一个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()返回分段函数空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆