How set background drawable programmatically in Android

JavaAndroidBackgroundDrawable

Java Problem Overview


To set Background:

RelativeLayout layout =(RelativeLayout)findViewById(R.id.background);
layout.setBackgroundResource(R.drawable.ready);

Is the best way to do it?

Java Solutions


Solution 1 - Java

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(ContextCompat.getDrawable(context, R.drawable.ready) );
} else {
    layout.setBackground(ContextCompat.getDrawable(context, 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.

UPDATE:
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).

UPDATE:
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 'com.android.support:support-v4:23.0.0' # or any version above

Or using ResourceCompat, in any API like below:

import android.support.v4.content.res.ResourcesCompat;
ResourcesCompat.getDrawable(getResources(), R.drawable.name_of_drawable, null);

Solution 2 - Java

Try this:

layout.setBackground(ContextCompat.getDrawable(context, R.drawable.ready));

and for API 16<:

layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));

Solution 3 - Java

RelativeLayout relativeLayout;  //declare this globally

now, inside any function like onCreate, onResume

relativeLayout = new RelativeLayout(this);	
relativeLayout.setBackgroundResource(R.drawable.view); //or whatever your image is
setContentView(relativeLayout); //you might be forgetting this

Solution 4 - Java

I'm using a minSdkVersion 16 and targetSdkVersion 23.
The following is working for me, it uses

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

Instead of using:

layout.setBackgroundResource(R.drawable.ready);

Rather use:

layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

getActivity() is used in a fragment, if calling from a activity use this.

Solution 5 - Java

You can also set the background of any Image:

View v;
Drawable image=(Drawable)getResources().getDrawable(R.drawable.img);
(ImageView)v.setBackground(image);

Solution 6 - Java

If you use AndroidX, you should use:

AppCompatResources.getDrawable(context, R.drawable.your_drawable)

Previous methods listed are deprecated.

Solution 7 - Java

If your backgrounds are in the drawable folder right now try moving the images from drawable to drawable-nodpi folder in your project. This worked for me, seems that else the images are rescaled by them self..

Solution 8 - Java

Use butterknife to bind the drawable resource to a variable by adding this to the top of your class (before any methods).

@Bind(R.id.some_layout)
RelativeLayout layout;
@BindDrawable(R.drawable.some_drawable)
Drawable background;

then inside one of your methods add

layout.setBackground(background);

That's all you need

Solution 9 - Java

if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN)
     layout.setBackgroundDrawable(getResources().getDrawable(R.drawable.ready));
else if(android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
     layout.setBackground(getResources().getDrawable(R.drawable.ready));
else
     layout.setBackground(ContextCompat.getDrawable(this, R.drawable.ready));

Solution 10 - Java

Give a try to ViewCompat.setBackground(yourView, drawableBackground)

Solution 11 - Java

try this.

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);

Solution 12 - Java

setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));

Solution 13 - Java

Try this code:

Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);

Solution 14 - Java

I have 4 fragment for splashscreen. i can change background by change fragment by this code

screen_main=(ConstraintLayout)view.findViewById(R.id.screen_main);
    screen_main.setBackground(getContext().getResources().getDrawable(R.color.bg_screen1));

Solution 15 - Java

Inside the app/res/your_xml_layout_file.xml

  1. Assign a name to your parent layout.
  2. Go to your MainActivity and find your RelativeLayout by calling the findViewById(R.id."given_name").
  3. Use the layout as a classic Object, by calling the method setBackgroundColor().

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionChad BinghamView Question on Stackoverflow
Solution 1 - JavaLazy NinjaView Answer on Stackoverflow
Solution 2 - JavaAhmadView Answer on Stackoverflow
Solution 3 - JavaSujay KumarView Answer on Stackoverflow
Solution 4 - JavaVostroView Answer on Stackoverflow
Solution 5 - JavaBhaskar Kumar SinghView Answer on Stackoverflow
Solution 6 - JavaFirzenView Answer on Stackoverflow
Solution 7 - JavaJordyView Answer on Stackoverflow
Solution 8 - JavaStephenView Answer on Stackoverflow
Solution 9 - JavaSameer ChamankarView Answer on Stackoverflow
Solution 10 - JavaUmair KhalidView Answer on Stackoverflow
Solution 11 - JavaFranklin CIView Answer on Stackoverflow
Solution 12 - JavaMohamed AbdelraZekView Answer on Stackoverflow
Solution 13 - JavaAshwin HView Answer on Stackoverflow
Solution 14 - Javasadegh salehiView Answer on Stackoverflow
Solution 15 - JavaVaggos PhlView Answer on Stackoverflow