在片段使用上下文 [英] Using context in a fragment

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

问题描述

如何获得上下文片段?

我需要用我的数据库,其构造函数中的上下文,但 getApplicationContext() FragmentClass.this 不工作,所以我能做些什么?

数据库构造

 公共数据库(上下文CTX)
{
    this.context = CTX;
    DBHelper =新DatabaseHelper(背景);
}


解决方案

您可以使用<一个href=\"http://developer.android.com/reference/android/app/Fragment.html#getActivity%28%29\"><$c$c>getActivity(),它会返回一个片段相关联的活动。结果
该活动是上下文的(因为活动扩展上下文)

How can I get the context in a fragment?

I need to use my database whose constructor takes in the context, but getApplicationContext() and FragmentClass.this don't work so what can I do?

Database constructor

public Database(Context ctx)
{
    this.context = ctx;
    DBHelper = new DatabaseHelper(context);
}

解决方案

You can use getActivity(), which returns the activity associated with a fragment.
The activity is a context (since Activity extends Context).

这篇关于在片段使用上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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