如何在运行时设置按钮的“android:drawableTop”属性

67
如何在运行时设置按钮的属性“android:drawableTop
8个回答

144

用法

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

设置图像(如果有)显示在文本左侧、上方、右侧和下方。如果不需要图像,则使用0。图像边界将被设置为它们的固有边界。

如果使用

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

设置图像(如果有)显示在文本左侧、上方、右侧和下方。如果不需要图像,则使用null。图像必须已经调用了setBounds(Rect)方法。


这个方法非常正确,但我想设置资源ID而不是可绘制对象。有没有办法做到这一点? - Maneesh
3
是的。使用 Resources resources = getResources(); Drawable drawable = resources.getDrawable(id); - Tanmay Mandal
Tanmay,我也在尝试做这件事,但仍然不确定如何使用代码来设置drawableTop。我知道如何获取drawable,但如何将其设置在按钮上呢? - Otto
这个在ExpandableListView组名中不起作用的原因是什么?这正是我想要使用的技巧,将组指示器放在右侧而不是左侧。 - OlivierM
9
感谢您的澄清。我使用了b.setCompoundDrawablesRelativeWithIntrinsicBounds(0,R.drawable.x,0,0)。该代码用于设置视图b中drawable的位置,其中R.drawable.x是要显示的drawable资源。具体而言,该代码将x drawable放置在视图b的顶部。 - Ryan Heitner
getDrawable()现在已被弃用。 - blackwolf

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

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

btnByCust.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View v) {


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

        }
    });

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

这个方法非常正确,但我想设置资源ID而不是可绘制对象。有没有办法做到这一点? - Maneesh
@Maneesh 请查看文档以获取该方法的详细信息。 - Bonatti

2

我使用这段代码来使用“Theme.Holo”按钮,并在左侧使用“自定义图像”,并使用从各种方式调用的函数更改它(即图像)。

protected void app_dibujarLogojuego() {
    if(bitmaplogojuego!=null){
        bitmaplogojuego.recycle();
        bitmaplogojuego=null;
    }
    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);
}

0
如果您正在使用 Kotlin,您可以使用扩展方法使代码看起来更加优雅。
fun TextView.setDrawableTop(iconId: Int) {
    val icon = this.context?.resources?.getDrawable(iconId)
    this.setCompoundDrawablesWithIntrinsicBounds(null, icon, null, null)
}

然后你可以像这样使用它:

// myTextView: TextView
myTextView.setDrawableTop(R.drawable.ic_happy)

0
 btn.setBackgroundResource(R.drawable.your_image_name_here);

0
创建一个像这样的扩展函数,并像这样设置顶部drawable
tvAccepted.setTopDrawable(R.drawable.ic_preparing_order_active)

fun TextView.setTopDrawable(icon: Int) {
    this.setCompoundDrawablesRelativeWithIntrinsicBounds(0,icon,0,0)
}

在哪里

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接