我调用了setCompoundDrawables
方法后,合成图标没有显示。
Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn.setCompoundDrawables(myDrawable, null, null, null);
有什么想法吗?
我调用了setCompoundDrawables
方法后,合成图标没有显示。
Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn.setCompoundDrawables(myDrawable, null, null, null);
有什么想法吗?
setCompoundDrawablesWithIntrinsicBounds
方法被添加于 API Level 3。 - Greg Ennis使用此方法(我已经测试过)。它效果很好。
Drawable image = context.getResources().getDrawable( R.drawable.ic_action );
int h = image.getIntrinsicHeight();
int w = image.getIntrinsicWidth();
image.setBounds( 0, 0, w, h );
button.setCompoundDrawables( image, null, null, null );
EditText#setCompoundDrawablesWithIntrinsicBounds
至少需要API 17。 - Krøllebølle图片显示为空白,因为它没有指定边界。您可以使用setCompoundDrawables()
方法,但在此之前,您需要使用Drawable.setBounds()
方法指定图片的边界。
示例设置到顶部:
view.setCompoundDrawablesWithIntrinsicBounds(
null,
getResources().getDrawable(R.drawable.some_img),
null,
null
);
参数顺序:(左,上,右,下)
再简单一点:
Drawable image = context.getResources().getDrawable(R.drawable.ic_action );
image.setBounds( 0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight() );
button.setCompoundDrawables( image, null, null, null );
由于您没有指定范围,因此图像未显示,因此您有两个选项。
第一种方法
使用setCompoundDrawablesWithIntrinsicBounds
方法,如下所示:
Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
btn. setCompoundDrawablesWithIntrinsicBounds(myDrawable, null, null, null);
第二种方法
在应用到TextView之前,可以对Drawable应用边界,如下所示
Drawable myDrawable = getResources().getDrawable(R.drawable.btn);
myDrawable.setBounds( 0, 0, myDrawable.getIntrinsicWidth(), myDrawable.getIntrinsicHeight());
btn.setCompoundDrawables(myDrawable, null, null, null);
就这样了。
它在API 22中已被弃用。
这段代码对我很有用:
Drawable drawable = ResourcesCompat.getDrawable(getResources(),R.drawable.wen, null);
drawable.setBounds(0, 0, drawable.getMinimumWidth(),
drawable.getMinimumHeight());
tv.setCompoundDrawables(drawable, null, null, null);
在Kotlin中:
1)设置drawable
:
val drawable = ContextCompat.getDrawable(context!!,R.drawable.ic_image)?.apply {
setBounds(0, 0, intrinsicWidth, intrinsicHeight)
}
或者
val drawable = ResourcesCompat.getDrawable(resources, R.drawable.ic_image, null)?.apply {
setBounds(0, 0, minimumWidth, minimumHeight)
}
2)设置TextView
:
textView.setCompoundDrawablesWithIntrinsicBounds(drawable, null, null, null)
或者
button.setCompoundDrawables(null, drawable, null, null)
setCompoundDrawablesWithIntrinsicBounds
会起作用。 - Akash BisariyaKotlin示例:
val myView = layoutInflater.inflate(R.layout.my_view, null) as TextView
myView.setCompoundDrawablesWithIntrinsicBounds(0, myDrawable, 0, 0)
padding
才能产生效果。 - Dr1KusetBounds(Rect)
方法。 - user1521536