静态的方式来获得“语境”在Android? [英] Static way to get 'Context' on Android?

查看:130
本文介绍了静态的方式来获得“语境”在Android?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法使用一个静态方法来得到当前的语境的实例?

Is there a way to get the current 'Context' instance by using a static method?

我在寻找这种方式,因为我讨厌每次更改时保存语境的实例。

I'm looking for that way because I hate saving the 'Context' instance each time it changes.

推荐答案

做到这一点:

在Android清单文件,声明如下。

In the Android Manifest file, declare the following.

<application android:name="com.xyz.MyApplication">

</application>

然后写的类:

Then write the class:

public class MyApplication extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApplication.context;
    }
}

现在到处打电话 MyApplication.getAppContext()来让你的应用程序上下文静态。

Now everywhere call MyApplication.getAppContext() to get your application context statically.

这篇关于静态的方式来获得“语境”在Android?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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