如何让我的活动范围内? [英] How to get my activity context?

查看:104
本文介绍了如何让我的活动范围内?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的不明白背后怎么这件事真的作品的想法,所以,如果我有一些类 A 需要一个类<$ C $的背景下C> B 延伸活动,我如何得到这方面?

I don't really get the idea behind how this whole thing works really, so if I have some class A that need the context of a class B which extends Activity, how do i get that context?

我在寻找一个更有效的方法,然后给出上下文作为参数传递给类 A 的构造,因为对于exsmple如果类 A 将有上百万的实例那么我们最终将有上百万的冗余指针到上下文,而我们应该能够以某种方式只有一个地方, getter函数...

I'm searching for a more efficient way then giving the context as a parameter to class A constructor, since for exsmple if class A is going to have millions of instances then we would end up having millions of redundant pointer to Context while we should be able somehow to have just one somewhere and a getter function...

推荐答案

您可以使用应用程序类(公共类android.application包),那就是:

You can use Application class(public class in android.application package),that is:

基类为那些谁需要保持全球应用程序状态。   您可以通过在指定其名字为自己的实现你的   AndroidManifest.xml中的标签,这将导致该类   被实例化时,你的过程中为您   应用程序/包创建的。

Base class for those who need to maintain global application state. You can provide your own implementation by specifying its name in your AndroidManifest.xml's tag, which will cause that class to be instantiated for you when the process for your application/package is created.

要使用这个类做的:

public class App extends Application implements OnInitListener {

    private static Context mContext;

    public static Context getContext() {
        return mContext;
    }

    public static void setContext(Context mContext) {
        this.mContext = mContext;
    }

    ...

}

在你的清单:

<application
        android:icon="..."
        android:label="..."
        android:name="com.example.yourmainpackagename.App" >
                       class that extends Application ^^^

在活动B:

public class B extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.sampleactivitylayout);

        App.setContext(this);
                  ...
        }
...
}

在A类:

Context c = App.getContext();

注意

通常没有需要继承的应用。在大多数情况下,   静态单身可以提供相同的功能在一个更模块化   方法。如果你单身需要一个全球范围内(例如注册   广播接收器),所述函数来检索它可以给出一个   Context,它内部使用Context.getApplicationContext()时,   首先构建单。

There is normally no need to subclass Application. In most situation, static singletons can provide the same functionality in a more modular way. If your singleton needs a global context (for example to register broadcast receivers), the function to retrieve it can be given a Context which internally uses Context.getApplicationContext() when first constructing the singleton.

这篇关于如何让我的活动范围内?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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