How set background drawable programmatically in Android
To set a background drawable programmatically in Android, you can use the setBackgroundDrawable method of the View class.
How to set background drawable programmatically in Android
To set a background drawable programmatically in Android, you can use the setBackground method of the View class.
Here is an example of how you can do this:
import android.widget.ImageView;
import androidx.core.content.ContextCompat;
ImageView imageView = new ImageView(this);
imageView.setBackground(ContextCompat.getDrawable(this, R.drawable.my_image));This will set the background of the ImageView to the drawable specified by the R.drawable.my_image resource.
Alternatively, you can use the setBackgroundResource method to set the background drawable using a resource ID:
imageView.setBackgroundResource(R.drawable.my_image);Note that getResources().getDrawable(int) and setBackgroundDrawable() have been deprecated. The modern approach is to use ContextCompat.getDrawable() from the AndroidX library, which automatically handles theming and API compatibility.
Here is an example of how you can use setBackgroundColor to set the background color:
imageView.setBackgroundColor(ContextCompat.getColor(this, R.color.my_color));ContextCompat.getColor() returns a resolved int, so setBackgroundColor(int) is the correct method to use. It is preferred over Color.parseColor() when you need to respect the current theme's color attributes, as it properly resolves color state lists and theme-aware values. If you specifically need to use setBackground(Drawable) for colors, wrap the color in a ColorDrawable: imageView.setBackground(new ColorDrawable(ContextCompat.getColor(this, R.color.my_color)));. Note that setBackground(Drawable) is available from API 16+. For API 14–15, use ViewCompat.setBackground() (requires androidx.core.view.ViewCompat import).