Chad Bingham Chad Bingham - 1 month ago 15x
Java Question

How set background drawable programmatically in Android

To set Background:

RelativeLayout layout =(RelativeLayout)findViewById(;

Is the best way to do it?


layout.setBackgroundResource(R.drawable.ready); is correct.
Another way to achieve it is to use the following:

final int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    layout.setBackgroundDrawable( getResources().getDrawable(R.drawable.ready) );
} else {
    layout.setBackground( getResources().getDrawable(R.drawable.ready));

But I think the problem occur because you are trying to load big images.
Here is a good tutorial how to load large bitmaps.

getDrawable(int ) deprecated in API level 22

getDrawable(int ) is now deprecated in API level 22. You should use the following code from the support library instead:

ContextCompat.getDrawable(context, R.drawable.ready)

If you refer to the source code of ContextCompat.getDrawable, it gives you something like this:

 * Return a drawable object associated with a particular resource ID.
 * <p>
 * Starting in {@link android.os.Build.VERSION_CODES#LOLLIPOP}, the returned
 * drawable will be styled for the specified Context's theme.
 * @param id The desired resource identifier, as generated by the aapt tool.
 *            This integer encodes the package, type, and resource entry.
 *            The value 0 is an invalid identifier.
 * @return Drawable An object that can be used to draw this resource.
public static final Drawable getDrawable(Context context, int id) {
    final int version = Build.VERSION.SDK_INT;
    if (version >= 21) {
        return ContextCompatApi21.getDrawable(context, id);
    } else {
        return context.getResources().getDrawable(id);

More details on ContextCompat

As of API 22, you should use the getDrawable(int, Theme) method instead of getDrawable(int).

If you are using the support v4 library, the following will be enough for all versions.

ContextCompat.getDrawable(context, R.drawable.ready)

You will need to add the following in your app build.gradle

compile '' # or any version above