Android: getApplicationContext() won't work in View subclass

时光怂恿深爱的人放手 提交于 2019-12-11 12:33:02

问题


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());

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


回答1:


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()

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!



来源:https://stackoverflow.com/questions/13824293/android-getapplicationcontext-wont-work-in-view-subclass

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!