setCompoundDrawablesWithIntrinsicBounds/android:drawableTop - Add a Drawable Above the Text in a TextView, in Java

setCompoundDrawablesWithIntrinsicBounds - How to Add a Drawable Above the Text in a TextView, in Java

setCompoundDrawablesWithIntrinsicBounds was added in API Level 3
Related XML Attribute: android:drawableTop

setCompoundDrawablesWithIntrinsicBounds (int left, int top, int right, int bottom)
Sets the Drawables (if any) to appear to the left of, above, to the right of, and below the text. Use 0 if you do not want a Drawable there. The Drawables' bounds will be set to their intrinsic bounds.

The drawable (image, picture, etc) will be displayed above the text in a TextView.

1. Ensure to change the minSDKVersion to 3, or greater.

2. Add a drawable named myImage

3. Add the following text to the TextView"This is an example with a drawable set above the text in a TextView."

6. Add the code below to the onCreate method.

myTextView.setCompoundDrawablesWithIntrinsicBounds(0,R.drawable.myImage,0,0);

7. At this point, the code will work. But to easier see the defines perimeter of the TextView, let's change the background color of the TextView to Gray. Hex: #808080

8. Compile and run!

This is using android:layout = "wrap_content"


9. You can also change the android:layout_width to match_parent, and you get the result below.

This is using android:layout = "match_parent"

Related Articles: