[英]best way to handle resources
I was kind of stuck trying to pass the resources to a subclass used on my Activity. 我有点想将资源传递给Activity上使用的子类。 I solved it in two ways, but not sure if one or both will lead to possible memory leaks.
我以两种方式解决了该问题,但不确定是否其中之一或两者都会导致可能的内存泄漏。 So here is what I have so far:
所以这是我到目前为止所拥有的:
-myactivity (the activity class) -myactivity(活动类)
-global (global class to the package, I'm using to to save global accesible variables) -global(程序包的全局类,我用来保存全局可访问变量)
-subclass (the subclass where I want to use a drawable resource) -subclass(我要使用可绘制资源的子类)
a) 一种)
public class global{
public static Resources appRes;
....
}
public class myactivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
global.resApp = this.getResources();
...
}
private void somewhere(){
subclass tmp = new subclass();
tmp.subclasmethod();
}
}
public class subclass{
public subclass(){...}
public void subclassmethod(){
Bitmap bmp = BitmapFactory.decodeResource(Global.appRes, R.drawable.myres);
...
}
}
b) b)
public class myactivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
}
private void somewhere(){
subclass tmp = new subclass(this.getContext());
tmp.subclasmethod();
}
}
public class subclass{
Context context;
public subclass(Context context){
this.context = context
...
}
public void subclassmethod(){
Bitmap bmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.myres);
...
}
}
Thanks in advance for you feedback. 预先感谢您的反馈。
If you want a global class to store application-wide values, you should at least not use your option a . 如果希望全局类存储应用程序范围的值,则至少不应使用选项a 。 Instead, take a look at the
Application
class, which is meant to help you with exactly this: 相反,请看一下
Application
类,它旨在帮助您实现这一点:
Base class for those who need to maintain global application state.
需要维护全局应用程序状态的人员的基类。
Otherwise, the alternative you suggest in option b is an OK way to do it. 否则,您在选项b中建议的替代方法是一种可行的方法。 At least if all you need is to pass along a reference to your application context so that you can access the resources.
至少,如果您需要做的就是传递对应用程序上下文的引用,以便您可以访问资源。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.