在分离的片段中获取上下文/活动? [英] Get context/activity in detached fragment?

查看:31
本文介绍了在分离的片段中获取上下文/活动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个类似的问题,其中大多数人给出了建议使用 getActivity() 来获取片段的上下文,但是如果片段被分离,如何获取对活动/上下文的引用(在这种情况下,getActivity() 返回 null)?

There is a similar question where most answers advice to use getActivity() in order to obtain the context of a fragment, but how to get a reference to the activity/context if the fragment is detached (in which case, getActivity() returns null)?

我的情况是我的片段启动了一个 AsyncTask,它在完成时调用我的片段的 onSuccess() 方法.但是我的片段的 onSuccess() 方法需要上下文才能显示 Toast 消息或访问共享首选项.那么有没有可靠的获取上下文的方法呢?

My situation is that my fragment starts an AsyncTask which, on completion, calls the onSuccess() method of my fragment. But my fragment's onSuccess() method requires a context in order to show a Toast message or to access the shared preferences. So is there a reliable way of obtaining the context?

我正在考虑的一种方法是将上下文对象传递给我的 AsyncTask 构造函数,并将其传递回我前面提到的 onSuccess() 回调方法 - 但这会导致内存泄漏吗?

One way I'm considering is to pass a context object into my AsyncTask constructor, and pass it back out to my aforementioned onSuccess() callback method - but could this result in a memory leak?

(注意 - 此处 的答案显示了如何检索当前活动,但同样,它需要一个有效的上下文.)

(NB - There's an answer here that shows how to retrieve the current activity but, again, it requires a valid context.)

推荐答案

在你的片段中使用这个:

Use this in your fragment:

private Context context;

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    context = activity;
}

然后在需要的地方使用 context.

then use context where you want.

这篇关于在分离的片段中获取上下文/活动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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