简体   繁体   中英

best way to handle resources

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.

If you want a global class to store application-wide values, you should at least not use your option a . Instead, take a look at the Application class, which is meant to help you with exactly this:

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. At least if all you need is to pass along a reference to your application context so that you can access the resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM