mContext.get().getApplicationContext()和getActivity()之间的区别 [英] Difference between mContext.get().getApplicationContext() and getActivity()

查看:133
本文介绍了mContext.get().getApplicationContext()和getActivity()之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么在我的片段中getActivity()可以工作,但mContext.getApplicationContext()不能工作?

Why in my fragment getActivity() works but mContext.getApplicationContext() does not?

mDobPickerDialog = new DatePickerDialog(getActivity(), new OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                mDobEditText.setText(mDateFormatter.format(newDate.getTime()));
            }

        },newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

我的mContext被声明并初始化为:

My mContext is declared and initialized as:

private Context mContext;

public DisplayProfileFragment(Context context) {
        super();
        mContext = context;
    }

推荐答案

getActivity()返回与该片段关联的活动.

getActivity() returns the Activity the fragment is associated with.

http://developer.android.com/reference/android/app/Fragment.html#getActivity()

getApplicationContext()返回全局Application上下文.

getApplicationContext() returns the global Application context.

http://developer.android.com/reference/android/content/Context.html#getApplicationContext()

关于为什么getApplicationContext()在您提供的代码中不起作用的原因,因为它不起作用.您正在针对当前活动创建一个对话框,需要该对话框的活动上下文,应将应用程序上下文用于诸如接收器之类的功能,应在销毁应用程序时销毁这些功能,而不是在销毁活动时销毁这些功能.

As for why getApplicationContext() doesn't work in the code you have provided, because it shouldn't. You are creating a dialog on the current activity, for which you need the activity context, the application context should be used for functions like receivers, functions that should be destroyed when the application is destroyed, not when the activity is destroyed.

这篇关于mContext.get().getApplicationContext()和getActivity()之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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