使用setCompoundDrawables为EditText设置图标时如何计算图标大小

10

当我像下面这样添加图标:

etComment = (EditText) findViewById(R.id.et_comment);
Drawable img = getResources().getDrawable( R.drawable.warning );
etComment.setCompoundDrawablesWithIntrinsicBounds( img, null, null, null );

输入图片说明 输入图片说明

这个图标会调整EditText的大小。我如何计算图像大小并将其放入EditText中,而不使EditText调整大小呢?

谢谢!


FunkTheMonk
使用setCompoundDrawables()而不是setCompoundDrawablesWithIntrinsicBounds() - 您需要手动设置绘图区域的边界。

我不明白如何手动计算边界。我已经获得了EditText的高度和宽度:

etComment = (EditText) findViewById(R.id.et_comment);
Drawable img = getResources().getDrawable( R.drawable.warning );
int size = etComment.getHeight();
img.setBounds(0, 0, size, size);
etComment.setCompoundDrawables( img, null, null, null );

但是在不同的屏幕尺寸下,我的结果不同。我如何计算图标的正确大小和填充?你能帮我吗?

3个回答

8
我认为您可以在不同的屏幕上使用不同大小的图片,并使用getMinimumWidth来设置边界。但我以前没有尝试过,也许对于.9 patch不太合适。
当您使用setCompoundDrawables时,您需要像这样编写代码:
Drawable img;
Resources res = getResources();
img = res.getDrawable(R.drawable.btn_img);
//You need to setBounds before setCompoundDrawables , or it couldn't display
img.setBounds(0, 0, img.getMinimumWidth(), img.getMinimumHeight());
btn.setCompoundDrawables(img_off, null, null, null); 

调整按钮中的图像大小很好用,非常感谢。 - Saqib
最后一行中的 img_off 是什么? - Nicks

5

我在这篇文章中找到了解决方案。

Drawable dr = this.getResources().getDrawable(R.drawable.warning);
Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
Drawable d = new BitmapDrawable(this.getResources(), Bitmap.createScaledBitmap(bitmap, 35, 35, true));

txtValue.setCompoundDrawablesWithIntrinsicBounds(d, null, null, null);

HTH, Milton


我遇到了这个错误:'java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable'。你能告诉我哪里出了问题吗? - Nicks
@sumitmehra 你应该提出一个单独的问题来获得答案。你之所以会遇到这个错误,是因为你正在将SVG作为位图可绘制对象加载。 - vanomart

3
使用setCompoundDrawables()代替setCompoundDrawablesWithIntrinsicBounds() - 您需要手动设置绘图的边界。

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