setCompoundDrawablesWithIntrinsicBounds/android:drawableRight - Add a Drawable to the Right of the text in a TextView, in Java

setCompoundDrawablesWithIntrinsicBounds - How to Add a Drawable to the Right of the text in a TextView, in Java

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

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 to the right of the text

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 to the right in a TextView."

6. Add the code below to the onCreate method.

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

7. Compile and run!

This is using android:layout_width = "wrap_content"

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

This is using android:layout_width = "match_parent"


Related Articles: