从片段访问活动 [英] Accessing the Activity from a Fragment

查看:139
本文介绍了从片段访问活动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图改变从一个片段活动标题(在这种情况下,它是一个 android.support.v4.app.Fragment )。为此,我保存活动中的一个属性上的片段时, onAttach()的呼吁片段。根据文档, onAttach()前应 onCreateView被称为(),我使用要求其中一些数据用来填满图。当我揭开序幕线程网络检索,我要指出的称号,所以我想从调用 this.activity.setTitle()片段。然而,不断抛出一个 NullPointerException异常。缺少什么我在这里?

I'm trying to change the activity title from a fragment (in this case, it's an android.support.v4.app.Fragment). To this end, I save the activity in an attribute on the fragment when onAttach() is called on the fragment. According to the docs, onAttach() should be called before onCreateView(), which I'm using to request some data used to fill up the view. When I kick off the thread for the network retrieval, I want to indicate that in the title, so I'm trying to call this.activity.setTitle() from the Fragment. However, that keeps throwing a NullPointerException. What am I missing here?

推荐答案

您可以通过访问活动的片段 getActivity()。它可以安全地尽快 onActivityCreated被称为()已呼吁片段。在此之前,它可能不是存在或可能没有得到充分尚未初始化。

You can access the Activity in a Fragment using getActivity(). It can be called safely as soon as onActivityCreated() was called on the Fragment. Before that, it might not be there or might not have been fully initialized yet.

如果您的线程之前启动,刚刚记下的事实某处的片段,只有经过 onActivityCreated 更改标题被调用。

If your thread starts before that, just note the fact somewhere in your Fragment and only change the title after onActivityCreated was called.

这篇关于从片段访问活动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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