将上下文作为DialogFragment的参数传递 [英] passing context as argument of DialogFragment

查看:271
本文介绍了将上下文作为DialogFragment的参数传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将上下文变量传递给DialogFragment?

我在对话框中使用了以下代码来传递字符串:

public static ConfirmDialog newInstance( String f) {
    ConfirmDialog d = new ConfirmDialog();

    Bundle args = new Bundle();
    args.putString("FILE_NAME", f);
    d.setArguments(args);

    return d;
}

但是我没有找到任何类似putString的函数来传递上下文.可以这样做吗?

解决方案

您的DialogFragment有一个非常方便的方法来获取Context实例:

getActivity()

Fragment#getActivity() 将返回Fragment附加到的Activity(它是Context)的实例.在Fragment的onAttach()被调用之后使用它.下表说明了 Fragment生命周期,如您所见,使用<从onCreate()onDestroy()的c8>应该是有效的呼叫.

有关更多信息,请阅读 Fragment 文档

it's possible to pass a context variable to a DialogFragment?

i've use this code inside dialog for passing a string:

public static ConfirmDialog newInstance( String f) {
    ConfirmDialog d = new ConfirmDialog();

    Bundle args = new Bundle();
    args.putString("FILE_NAME", f);
    d.setArguments(args);

    return d;
}

but i don't find any function like putString for passing context. It's possible to do that?

解决方案

Your DialogFragment has a very handy method for getting a Context instance:

getActivity()

Fragment#getActivity() will return the instance of the Activity (which is a Context) that the Fragment is attached to. Use it after the Fragment's onAttach() is called. The below chart illustrates the Fragment lifecycle, as you can see, using getActivity() from onCreate() to onDestroy() should be a valid call.

For more information, read the Fragment documentation

这篇关于将上下文作为DialogFragment的参数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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