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

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

问题描述

如何获取片段中的上下文?

我需要使用其构造函数接受上下文的数据库,但是 getApplicationContext()FragmentClass.this 不起作用,我该怎么办?>

数据库构造器

公共数据库(上下文ctx){this.context = ctx;DBHelper = new DatabaseHelper(context);}

解决方案

您可以使用 getActivity(),它返回与 fragment 关联的活动.
Activity 是一个 context (因为 Activity extends Context).

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天全站免登陆