0

I was kind of stuck trying to pass the resources to a subclass used on my 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)

-global (global class to the package, I'm using to to save global accesible variables)

-subclass (the subclass where I want to use a drawable resource)

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)

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.

4

1 回答 1

1

如果你想要一个全局类来存储应用程序范围的值,你至少不应该使用你的选项a。相反,请查看该Application课程,该课程旨在帮助您解决此问题:

需要维护全局应用程序状态的基类。

否则,您在选项b中建议的替代方案是一种可行的方法。至少,如果您只需要传递对应用程序上下文的引用,以便您可以访问资源。

于 2010-11-30T12:29:50.350 回答