差BTN mContext.get()。getApplicationContext()和getActivity() [英] Difference btn mContext.get().getApplicationContext() and getActivity()

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

问题描述

为什么在我的片段getActivity()的作品,但mContext.getApplicationContext()不?

  mDobPickerDialog =新DatePickerDialog(getActivity(),新OnDateSetListener(){            公共无效onDateSet(查看的DatePicker,年整型,诠释monthOfYear,诠释请将dayOfMonth){
                日历newDate = Calendar.getInstance();
                newDate.set(年,monthOfYear,请将dayOfMonth);
                mDobEditText.setText(mDateFormatter.format(newDate.getTime()));
            }        },newCalendar.get(Calendar.YEAR),newCalendar.get(的Calendar.MONTH),newCalendar.get(Calendar.DAY_OF_MONTH));

我mContext声明和初始化:

 私人语境mContext;公共DisplayProfileFragment(上下文的背景下){
        超();
        mContext =背景;
    }


解决方案

getActivity()返回片段与相关联的活动。

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

getApplicationContext()返回在全球范围内应用。

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

至于为什么getApplicationContext()无法在您提供的code工作,因为它不应该。所创建的当前活动,为此需要在活动上下文一个对话,应用程序上下文应该用于像接收机,应当应用程序被破坏,而不是当该活动被破坏被破坏的功能的功能。

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));

My mContext is declared and initialized as:

private Context mContext;

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

解决方案

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

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

getApplicationContext() returns the global Application context.

http://developer.android.com/reference/android/content/Context.html#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.

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

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