【问题标题】:The this keyword in the context below android programmingandroid编程下面上下文中的this关键字
【发布时间】:2015-02-28 14:19:51
【问题描述】:

您好,我想弄清楚下面的代码是如何工作的及其含义:

    public Context mContext;
    private Common mApp;
    public Activity mActivity;

    mContext = this;
    mActivity = this;
    mApp = (Common) mContext.getApplicationContext()

为了我调用一个方法,我需要创建该类的一个对象,如下所示

  Context mContext = new Context();

and then i would be able to invoke the method getAppliationContext as shown above:

 mContext.getApplicationContext()

有人可以为我解释一下吗,以及上面的 this 关键字是如何应用的。据我所知,this 关键字是对对象本身的引用。 我也不明白“mApp”是如何被用作一个对象来调用下面的各种方法的:

     int startCount = mApp.getSharedPreferences().getInt("START_COUNT", 1);
    mApp.getSharedPreferences().edit().putInt("START_COUNT", startCount+1).commit();

尚未使用 new 关键字创建它,我认为我需要执行以下操作才能使用 mApp 调用方法:

Common mApp = new Common();

这样我就可以做到了

    int startCount = mApp.getSharedPreferences().getInt("START_COUNT", 1);
    mApp.getSharedPreferences().edit().putInt("START_COUNT", startCount+1).commit(); 

我认为我的目标是,是否有其他方法可以在不使用 new 关键字的情况下创建对象。

【问题讨论】:

    标签: android android-activity android-context


    【解决方案1】:

    您对 this 关键字的看法完全正确。

    Activity 类扩展了 Context 类。因此this 关键字可以在Activity 类中用于引用Activity 对象和Context 对象,因为Activity 类型的对象只是Context 的扩展版本,因此具有其所有方法和变量继承。见这里:http://developer.android.com/reference/android/app/Activity.html

    我从未在 Android API 中看到 Common,但它是从 Context 对象转换而来的,因此我会将它视为 Context 对象。您不必实例化 Context 对象来调用其方法的原因是,在此示例中,您已经为 mApp 分配了一个 Context 实例。

    【讨论】:

    • 感谢您的洞察
    • 感谢您的见解,这是否意味着使用 this 关键字将引用 mContext 和 mActivity 分配给对象: mContext = this; mActivity = this;
    • 没错。 mContextmActivity 将被分配它们所写的类的对象实例。
    • 通过这样做,我们可以调用该类或已通过使用这些引用扩展的类的方法?我们不必使用 new 关键字?
    • 是的,你可以,不,你不必使用 new,因为 new 关键字只会在类对象中生成该类的新对象实例。在本例中,您引用的是已创建的对象实例。
    【解决方案2】:

    您可以通过在任何扩展上下文对象的类上调用getApplicationContext() 来获取上下文。 顾名思义,它是应用程序/对象当前状态的上下文。

    例如:ActivityIntentServiceBroadcastReceiver

    Context context=getApplicationContext();
    

    获取上下文对象后,可以在任意类内部调用上下文类方法。

    例如:

     context.startActivity();
     context.getSharedPrefereces();
     context.getSystemService(LAYOUT_INFLATER_SERVICE);      
     context.getContentResolver().query(uri, ...);
    

    【讨论】:

    • 谢谢,这是否意味着 getApplicationContext() 方法返回一个 Context 类型的对象?我们将这个对象分配给引用上下文?
    • @kobewarui 是的,它返回一个 Context 类型的对象
    猜你喜欢
    • 1970-01-01
    • 2018-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-28
    • 2015-01-13
    • 2022-11-18
    相关资源
    最近更新 更多