349

To set Background:

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

Is the best way to do it?

Chad Bingham
  • 32,650
  • 19
  • 86
  • 115
  • 3
    Thank you! your question and all helpful answers helped me set the background resource of an image button inside a **widget**. here's a sample code in case someone is interested: `remoteViews.setInt(R.id.btn_start,"setBackgroundResource", R.drawable.ic_button_start);` – Sam Aug 17 '18 at 18:17
  • 1
    Kotlin Solution for whom may need : https://stackoverflow.com/a/54495750/6247186 – Hamed Jaliliani Feb 02 '19 at 18:16

14 Answers14

591

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);
Lazy Ninja
  • 22,342
  • 9
  • 83
  • 103
  • 4
    'getDrawable(int)' is deprecated. – S.M_Emamian Aug 05 '15 at 08:29
  • Hey, I am trying to do a task only if the background image of an image button is a certain drawable resource. How can I compare... I've tried `if(buttonBackground.equals(R.drawable.myDrawable))` where `Drawable buttonBackground = myButton.getBackground();`I get this error: http://snag.gy/weYgA.jpg – Ruchir Baronia Nov 28 '15 at 21:53
  • You would also need `myActivity.getTheme()` for the latest version of method, instead of null parameter: `myView.setBackground( getResources().getDrawable(R.drawable.my_background, activity.getTheme()));` – Zon Jul 26 '17 at 12:34
  • or you can use `AppCompatResources.getDrawable(this.getContext(), resId)` instead, Google already implemented it to in `AppCompat*` widget/view, e.g: `android.support.v7.widget.AppCompatCheckBox` – mochadwi Mar 05 '20 at 16:26
119

Try this:

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

and for API 16<:

layout.setBackgroundDrawable(ContextCompat.getDrawable(context, R.drawable.ready));
Ahmad
  • 69,608
  • 17
  • 111
  • 137
20
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
Sujay Kumar
  • 520
  • 8
  • 19
12

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.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Vostro
  • 197
  • 2
  • 3
9

You can also set the background of any Image:

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

If you use AndroidX, you should use:

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

Previous methods listed are deprecated.

Firzen
  • 1,909
  • 9
  • 28
  • 42
3
setBackground(getContext().getResources().getDrawable(R.drawable.green_rounded_frame));
Mohamed AbdelraZek
  • 2,503
  • 4
  • 25
  • 36
2

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..

Jordy
  • 1,764
  • 1
  • 22
  • 32
  • 5
    Well if you haven't got a copy of the images you need to use in the project in HD quality, why let android rescale them to crappy quality by using the normal drawable folder. And even do the question is old, if it still pops up in Google than posting something new in it is ok imho. – Jordy Apr 17 '14 at 13:29
1

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

Stephen
  • 7,994
  • 9
  • 44
  • 73
1
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));
Unheilig
  • 16,196
  • 193
  • 68
  • 98
1

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

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Umair Khalid
  • 2,259
  • 1
  • 21
  • 28
1

try this.

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);
Franklin CI
  • 159
  • 1
  • 9
0

Try this code:

Drawable thumb = ContextCompat.getDrawable(getActivity(), R.mipmap.cir_32);
mSeekBar.setThumb(thumb);
CroMagnon
  • 1,218
  • 7
  • 20
  • 32
Ashwin H
  • 695
  • 7
  • 24
-1

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().
Vaggos Phl
  • 55
  • 3