Skip to main content

How to set a compound drawable (image) in a TextView in Kotlin Android

How to set a compound drawable (image) in a TextView in Kotlin Android.

Here is a step-by-step tutorial on how to set a compound drawable (image) in a TextView in Kotlin Android:

  1. Create a new Android project in Android Studio.
  2. Open the layout file (activity_main.xml) where you want to add the TextView with the compound drawable.
  3. Add a TextView element to the layout file. Make sure to give it an id for later reference. For example:
<TextView
android:id="@+id/myTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Compound Drawable!"
/>
  1. In the MainActivity.kt file, find the reference to the TextView by using the findViewById() method in the onCreate() method. For example:
val myTextView = findViewById<TextView>(R.id.myTextView)
  1. Now you can set the compound drawable to the TextView using the setCompoundDrawables() method. This method takes four parameters: left, top, right, and bottom drawables. You can pass null to any of these parameters if you don't want to set a drawable in that position. For example, to set a drawable on the left side of the text, use the following code:
val drawableLeft = resources.getDrawable(R.drawable.ic_my_drawable)
myTextView.setCompoundDrawablesWithIntrinsicBounds(drawableLeft, null, null, null)
  1. If you want to set drawables on other positions, you can pass the appropriate drawables to the setCompoundDrawablesWithIntrinsicBounds() method. For example, to set a drawable on the right side of the text, use the following code:
val drawableRight = resources.getDrawable(R.drawable.ic_my_drawable)
myTextView.setCompoundDrawablesWithIntrinsicBounds(null, null, drawableRight, null)
  1. You can also set drawables on the top or bottom positions by passing the appropriate drawables to the setCompoundDrawablesWithIntrinsicBounds() method. For example, to set a drawable on the top side of the text, use the following code:
val drawableTop = resources.getDrawable(R.drawable.ic_my_drawable)
myTextView.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop, null, null)
  1. If you want to set compound drawables with custom sizes, you can create a new drawable object with the desired size using the setBounds() method. For example, to set a drawable on the left side of the text with a custom size, use the following code:
val drawableLeft = resources.getDrawable(R.drawable.ic_my_drawable)
drawableLeft.setBounds(0, 0, 50, 50)
myTextView.setCompoundDrawables(drawableLeft, null, null, null)
  1. Finally, run the app on an Android device or emulator to see the TextView with the compound drawable.

That's it! You have successfully set a compound drawable (image) in a TextView in Kotlin Android.