开发者

Is there anything wrong with using a public static Context? ( Regarding getResources() )

Recently I ran into a problem when trying to load an bitmap outside of my main class. I found that within my main class I could pass this as a Context to any given function allowing me to call getResources() from within that function. There are a couple of things about this which don't make sense to me.

The keyword "this" simply refers to the current object the function is running in, right? If so, how can I pass my main class as a Context by using "this"? It doesn't even have a Context in it. I am using "extends Activity", but Activity doesn't seem to contain any function called getResources() in it either.

I found a workaround which allows me to do what I want a bit easier which is to declare a public static Context appContext; within my main class. Then, within onCreate() I set appContext = this; Then, from elsewhere I can call MainActivity.appContext.getResources() whenever I need it. So, I really have a few questions here.

  1. Why are MainActivity(my main class) and appContext not essentially the same thing when appContext is set to "this" from inside MainActivity (There is no such thing as MainActivity.getResources())

  2. Is this unsafe to do? Could this cause any potential problems in my program?

  3. Is there a way to load images without having to use getResources()?

  4. What is the p开发者_StackOverflowroper way to show my code in this website? The standard I am used to ([code][/code] tags) don't seem to work properly in the preview, so I am assuming it is handled differently here. The formatting help page says to simply use four spaces, but that doesn't seem to show any difference in the preview section either.

EDIT: I just read in another thread somebody said

now everything depends on your main activity's onCreate method having been called.

That got me thinking. Under what circumstances would onCreate not be called? It seems like if it wasn't called the program would stop working properly in many ways not related to having a static variable initialized inside it(ie. setContentView would not be called).

So assuming that there is nothing wrong with doing it this way, the only drawback I can find, is that "MainActivity.appContext.getResources()" is a lot to type to call a function. Is there any way to create a sort of alias for this? I suppose I could create a function which simply calls that, but that just seems silly.


If you look here you see that activity is a subclass of Context.

You can format code with a backtic, or just use the {} buttons on the editor. See the markdown manual for more info.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜