Java

How set background drawable programmatically in Android

27 September 2026 · 6 min read

How set background drawable programmatically in Android

Styling your Android app’s user interface is crucial for creating a positive user experience. A key aspect of this is controlling the background of your views. While setting background drawables in XML is common, dynamically changing them programmatically offers greater flexibility and control. This allows you to respond to user interactions, system events, or data changes, creating a more interactive and engaging app. This article dives into the intricacies of setting background drawables programmatically in Android, offering practical examples and best practices.

Understanding Drawable Resources

Drawables in Android represent visual resources, including images (PNG, JPG, GIF), shapes, and state lists. They are typically stored in your project’s res/drawable directory. Accessing and applying these drawables programmatically opens a world of possibilities for dynamic UI manipulation.

Understanding the different types of drawables, like shape drawables (which allow you to create custom shapes using XML), state list drawables (for defining different drawables based on the view’s state), and layer list drawables (for combining multiple drawables), is essential for leveraging the full power of programmatic background manipulation.

Knowing how to access these various drawable types programmatically enables you to create visually rich and responsive user interfaces.

Setting a Background Drawable

Setting a background drawable programmatically is straightforward. You obtain a reference to the desired drawable using ContextCompat.getDrawable() and then apply it to your view’s background using setBackground(). This allows you to swap backgrounds dynamically, responding to user actions or application state changes.

Here’s a simple example:

java ImageView myImageView = findViewById(R.id.my_image_view); Drawable myDrawable = ContextCompat.getDrawable(this, R.drawable.my_image); myImageView.setBackground(myDrawable); This snippet retrieves the drawable with the ID my_image from your resources and sets it as the background for the ImageView. This approach provides dynamic control over the appearance of your views, enabling visually engaging user experiences.

Working with Different Drawable Types

Android offers various drawable types, each serving a specific purpose. Shape drawables, for instance, allow you to create custom shapes programmatically. State list drawables enable you to define different backgrounds for different view states (e.g., pressed, focused). Layer list drawables let you combine multiple drawables, creating complex visuals.

Programmatically manipulating these different drawable types unlocks powerful UI customization options. For instance, you could dynamically change the background shape of a button based on user interaction, creating a visually engaging feedback mechanism. Or, you could use state list drawables to provide visual cues for disabled buttons.

Mastering these techniques empowers you to create truly dynamic and responsive user interfaces.

Handling Compatibility

When working with drawables, consider compatibility across different Android versions. Older versions may require different approaches for certain drawable types. Using ContextCompat.getDrawable() ensures compatibility across a wider range of Android versions, mitigating potential issues.

For instance, using vector drawables, introduced in API 21, requires careful handling for backward compatibility. Employing compatibility libraries or alternative approaches ensures your app functions correctly on older devices.

Prioritizing backward compatibility ensures a consistent user experience across a broad range of devices.

Best Practices and Common Pitfalls

When setting background drawables programmatically, a few best practices can help you avoid common pitfalls. Ensure you are working with the correct context to access resources properly. Be mindful of resource management to prevent memory leaks, especially when dealing with large images. Optimize your drawables for different screen densities to maintain visual quality across various devices. Testing your implementation on different devices and Android versions ensures a consistent user experience.

  • Use ContextCompat.getDrawable() for compatibility.
  • Optimize images for different screen densities.
  1. Get the view you want to modify.
  2. Obtain the drawable resource.
  3. Set the drawable as the background.

Consider using libraries like Glide or Picasso for efficient image loading and caching, particularly when dealing with network images. These libraries handle tasks like resizing and caching automatically, optimizing performance and reducing development time. Remember to carefully consider image sizes and compression to minimize the impact on app size and performance.

Featured Snippet: To set a background drawable programmatically in Android, use ContextCompat.getDrawable(context, R.drawable.your_drawable) to retrieve the drawable and view.setBackground(drawable) to apply it to the view.

Learn more about Android Development[Infographic Placeholder - Illustrating different drawable types and their usage]

FAQ

Q: What is the difference between setting a background in XML and programmatically?

A: Setting a background in XML is static, applied during layout inflation. Programmatically setting the background offers dynamic control, allowing changes during runtime based on user interaction or other events.

By mastering the techniques outlined in this article, you can leverage the power of programmatic background manipulation to create dynamic, engaging, and visually appealing Android applications. Explore the provided resources to deepen your understanding and refine your skills. Experiment with different drawable types and explore how they can enhance your app’s user interface.

This targeted approach empowers you to create rich and adaptive user interfaces, ensuring a positive and engaging user experience. Dive deeper into Android’s styling capabilities and explore how background manipulation can elevate your app’s design.

Question & Answer :
To set Background:

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

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(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);