【发布时间】:2011-02-07 09:29:41
【问题描述】:
如何在运行时设置按钮的属性“android:drawableTop”
【问题讨论】:
如何在运行时设置按钮的属性“android:drawableTop”
【问题讨论】:
使用
button.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
设置可绘制对象(如果有)显示在文本的左侧、上方、右侧和下方。如果您不想要 Drawable,请使用 0。 Drawable 的边界将设置为其固有边界。
如果你使用
button.setCompoundDrawables(left, top, right, bottom);
设置可绘制对象(如果有)显示在文本的左侧、上方、右侧和下方。如果您不想要 Drawable ,请使用 null 。 Drawables 必须已经调用了setBounds(Rect)。
【讨论】:
Drawable top = getResources().getDrawable(R.drawable.image);
button.setCompoundDrawablesWithIntrinsicBounds(null, top , null, null);
【讨论】:
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);
}
});
【讨论】:
Button button = (Button) findViewById(R.id.button);
button.setCompoundDrawables(left, top, right, bottom);
【讨论】:
我使用此代码来使用左侧带有“自定义图像”的“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);
}
【讨论】:
btn.setBackgroundResource(R.drawable.your_image_name_here);
【讨论】:
如果你在使用 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)
【讨论】:
像这样创建一个扩展函数并像这样设置顶部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)
【讨论】: