“Do not place Android context classes in static fi

2019-05-27 12:04发布

"Do not place Android context classes in static fields; this is a memory leak (and also breaks Instant Run)" is shown while making any Android control static. Any better way to access an android control(like TextView) from other class other than creating an object of Parent class or making it(TextView) static?

2条回答
劳资没心,怎么记你
2楼-- · 2019-05-27 12:43

I'm not sure if what you are doing is valid, but you can use an event bus, such as Otto to send events from objects to objects (such as from a Service to an Activity)

And you can have your own Application-derived object, this will be a singleton existing all the time while your program is alive, so you can have static fields in there.

查看更多
太酷不给撩
3楼-- · 2019-05-27 12:57

As we know, the Application or MultiDexApplication class always remains active in memory, so we do not need to make our objects or variables as static, instead just declare them as normal(non-static) one, and call by creating an object of that application class, ie. instead of calling it directly as a static..

Wrong Way:

AppClass.myObj = 1;
var = AppClass.myObj;

Right Way:

AppClass appClass = (AppClass)getApplicationContext();
appClass.myObj=1;

and

var= appClass.myObj;
查看更多
登录 后发表回答