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.
Here is an example of how you can do this:
ImageView imageView = new ImageView(this);
imageView.setBackgroundDrawable(getResources().getDrawable(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 the setBackgroundDrawable
and setBackgroundResource
methods have been deprecated in favor of the setBackground
method, which allows you to set the background using a drawable or a color value.
Here is an example of how you can use the setBackground
method to set the background drawable:
imageView.setBackground(getResources().getDrawable(R.drawable.my_image));
And here is an example of how you can use the setBackground
method to set the background color:
imageView.setBackgroundColor(Color.parseColor("#ff0000"));
Note that the setBackground
method is available in API level 16 and higher.