安卓:getApplicationContext()将不会在查看子工作 [英] Android: getApplicationContext() won't work in View subclass

查看:128
本文介绍了安卓:getApplicationContext()将不会在查看子工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我做了延伸查看类DrawView,我想画与分该类一些图形我存储为int数组
我提出这个阵列像一种公共变量与的帮助下如何声明全局变量
所以,当我想要得到与MyApp的在活动连接,改变我的数组,我只是用

So i have made a class DrawView which extends View and i want to draw some graph in that class with the points i stored as int array i made this array like a sort of public variable with the help of How to declare global variables So when i want to get connected with MyApp in Activity and change my array, i simply use

MyApp appState = ((MyApp)getApplicationContext());

但问题是,当我在我的 DrawView.java 类调用它不会起作用。
任何的IDE如何解决此问题?

but the problem is that this won't work when i call it in my DrawView.java class. Any ides how to solve this?

推荐答案

我真的不知道为什么答案是这样了投票,因为它不是一个很好的解决方案。
Application对象是运行应用程序,而不是存储数据,你可以用一个简单的Singleton对象解决这个问题要容易得多,试试这个:

I really don't know why that answer is so up voted as it's not a good solution. The Application object is to run the Application, not to store data, you can solve this MUCH easier with a simple Singleton object, try this:

    public Class MyData{

        private int[] data;
        private static MyData me;

        public int[] getData(){
           return data;
        }

        private MyData(){} // private constructor

        public MyData get() {}
            if(me==null) me = new MyData();
            return me;
        }
    }

比任何对象,你可以调用:

than from any object you can call:

    int[] data = MyData.get().getData()

和随意扩大到不仅仅是一个INT [] ...把​​你想成为全球访问的任何其他对象。但要记住,不要让参考上下文!

and feel free to expand to more than just a int[] ... put any other object that you want to be globally accessible. But remember, DO NOT KEEP REFERENCES TO THE CONTEXT!

这篇关于安卓:getApplicationContext()将不会在查看子工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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