如何在运行时设置按钮的属性“
android:drawableTop
”用法
button.setCompoundDrawablesWithIntrinsicBounds(left, top, right, bottom);
设置图像(如果有)显示在文本左侧、上方、右侧和下方。如果不需要图像,则使用0。图像边界将被设置为它们的固有边界。
如果使用
button.setCompoundDrawables(left, top, right, bottom);
设置图像(如果有)显示在文本左侧、上方、右侧和下方。如果不需要图像,则使用null。图像必须已经调用了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);
}
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)
btn.setBackgroundResource(R.drawable.your_image_name_here);
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)