上下文之间的区别 [英] Difference between context

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

问题描述

可能重复:结果
  <一href=\"http://stackoverflow.com/questions/1026973/android-whats-the-difference-between-the-various-methods-to-get-a-context\">Android - 什么是拿到一个Context的各种方法之间的差异

我想知道什么是两者的区别:这个 ClassName.this getApplicationContext() myContext

I want to know what's the difference between using this, ClassName.this, getApplicationContext() or myContext?

什么是使用每个如下面的吐司

What are the effects of using each as context in the Toast below?

public class ClassName extends Activity {
    final ClassName myContext = this;
    ...
    public void onCreate(Bundle savedInstanceState) {
    ...
    button.setOnClickListener(new OnClickListener(){
        public void onClick(View v) {
            Toast.makeText(getApplicationContext(), "This is a toast", Toast.LENGTH_LONG).show();
        }

    });
    }

你能指出我为背景的详细说明?我已阅读罗曼盖伊的帖子 rel=\"nofollow\">。也许几个例子可以帮助:)

Can you point me to a detailed explanation for contexts? I have read Romain Guy's post here. Maybe a few more examples could help :)

推荐答案

活动应用程序都是从上下文类派生的。因此,这个来代替,当你code或者是一个活动或应用程序类的一部分Context对象的使用。其中之一的外(在片段,例如),你可以调用 getActivity()来获得封闭的活动(以及使用它作为一个Context)。 getApplicationContext()是你的活动是如何得到一个上下文比自己更广泛。如果你需要使用一个Context超出了活动的生命周期,你得到它(例如,通过它变成一个长期运行的后台线程),你可能想这一点。

Activity and Application are both derived from the Context class. Therefore, this can be used in place of a Context object when your code is part of either an Activity or Application class. Outside of one of these (in a Fragment, for example), you can call getActivity() to obtain the enclosing Activity (and use it as a Context). getApplicationContext() is how your Activity gets a Context broader than itself. You might want this if you need to use a Context beyond the lifetime of the Activity where you got it (for example, passing it into a long-running background thread).

您可能不需要在祝酒词中的应用程序上下文。但是,通过使用它,你的面包应该能够保持可见和不造成任何崩溃,即使你退出活动,你开始吧。

You probably don't need the Application context in your Toast. But, by using it, your Toast should be able to remain visible and not cause any crashes even if you leave the Activity where you started it.

这篇关于上下文之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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