[ACCEPTED]-How to set property "android:drawableTop" of a button at runtime-layout

Accepted answer
Score: 144


button.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);

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

If 5 you use

button.setCompoundDrawables(left, top, right, bottom);

Sets the Drawables (if any) to appear 4 to the left of, above, to the right of, and 3 below the text. Use null if you do not want 2 a Drawable there. The Drawables must already 1 have had setBounds(Rect) called.

Score: 56
Drawable top = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);


Score: 23
final Drawable drawableTop = getResources().getDrawable(R.drawable.btn_check_buttonless_on);

btnByCust.setOnClickListener(new OnClickListener() {

public void onClick(View v) {

 btnByCust.setCompoundDrawablesWithIntrinsicBounds(null, drawableTop , null, null);



Score: 4
        Button button = (Button) findViewById(R.id.button);
        button.setCompoundDrawables(left, top, right, bottom);


Score: 2

I use this code for use the "Theme.Holo" button 3 with a "Custom image" at left and change 2 it (the image)with a function that is called 1 from various ways.

protected void app_dibujarLogojuego() {
    Drawable LOGO = null;
    if(verjuego.equals("COSA1")){  LOGO = getResources().getDrawable(R.drawable.img_logo_COSA1);  }
    if(verjuego.equals("COSA2")){  LOGO = getResources().getDrawable(R.drawable.img_logo_COSA2);  }
    if(verjuego.equals("COSA3")){  LOGO = getResources().getDrawable(R.drawable.img_logo_COSA3);  }
    if(verjuego.equals("COSA4")){  LOGO = getResources().getDrawable(R.drawable.img_logo_COSA4);  }

    BUTTON_DECLARED_ID.setCompoundDrawablesWithIntrinsicBounds(LOGO, null , null, null);
Score: 0


Score: 0

If you are using Kotlin, you can use extension 2 method to make things look elegant.

fun TextView.setDrawableTop(iconId: Int) {
    val icon = this.context?.resources?.getDrawable(iconId)
    this.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null)

Then 1 you can use it like this:

// myTextView: TextView
Score: 0

Create an extension function like this and 1 set top drawable like this


fun TextView.setTopDrawable(icon: Int) {


setCompoundDrawablesRelativeWithIntrinsicBounds(left/start, top, right/end, bottom)

More Related questions