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

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

问题描述

我怎样才能在一个片段的背景下?我需要用我的数据库,其构造函数中的背景之下, 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 dont 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天全站免登陆