Android
Programming
Drawable
Background
Tutorial

How set background drawable programmatically in Android

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

In Android app development, customizing the UI dynamically involves understanding and manipulating views programmatically. One common task is setting a background drawable for a View. Doing this programmatically allows for greater flexibility, such as changing backgrounds based on user actions, themes, or other runtime conditions.

Understanding Drawables in Android

The `Drawable` class is a general abstraction for "something that can be drawn." It is the base class for different types of resources, like images (`BitmapDrawable`), shapes (`ShapeDrawable`), colors (`ColorDrawable`), or layers (`LayerDrawable`). In Android development, we can define a drawable resource in XML and also manipulate it in code.

Key Types of Drawables:

  • BitmapDrawable: Represents a bitmap image.
  • ColorDrawable: Represents a color or a color state list.
  • ShapeDrawable: Draws simple shapes using the shape specified in the XML.
  • LayerDrawable: Draws multiple other drawables layered on top of each other.

Setting a Background Drawable Programmatically

The `setBackground()` or `setBackgroundResource()` methods of the `View` class are commonly used to set a drawable as the background of a view.

Steps to Set a Background Drawable:

  1. Reference the View - Identify the view whose background you wish to change.
  2. Retrieve the Drawable - Obtain a Drawable object either from resources or create it programmatically.
  3. Set the Drawable - Use `setBackground()` method to set the drawable.

Example

Below is an example of setting a drawable from resources:

  • API Level: While `setBackground()` is evident for devices running API Level 16 (Jelly Bean) and above, `setBackgroundDrawable()` is used for backporting to lower API levels. However, it is deprecated in API Level 16 and above.
  • Resource Management: Always ensure that you aren’t hardcoding drawable resources as it can lead to unoptimized memory utilization. Use animation states or drawable states for condition-based changes.
  • Nullable Drawables: Always check for nullability when using `getDrawable`.

Related reading
Free course
Beginner
7 lessons
2 hours
Tackling System Design Interview Problems

A short course that equips you with the skills to approach system design interviews methodically.

Start the free course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.