为EditText使用setCompoundDrawables时计算图像大小

Igo*_*rOK 10 android android-layout

当我添加如下图标时:

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

在此输入图像描述 在此输入图像描述

图标调整EditText的大小.如何在不调整EditText大小的情况下计算img大小并将其放入EditText?

谢谢!


FunkTheMonk
使用setCompounDrawables()而不是setCompoundDrawablesWithIntrinsicBounds() - 您必须手动设置drawable的边界.

我不明白如何手动计算Bounds.我有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 );
Run Code Online (Sandbox Code Playgroud)

但我在不同的屏幕尺寸上有不同的结果.我如何计算图标的正确尺寸和填充?请你帮助我好吗?

Wan*_*721 8

我认为你可以为不同的屏幕使用不同大小的图片,并使用getMinimumWidth设置Bounds.But我之前没有尝试过,可能是不适合.9补丁.

使用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); 
Run Code Online (Sandbox Code Playgroud)


Mil*_*ton 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);
Run Code Online (Sandbox Code Playgroud)

HTH, 米尔顿


Fun*_*onk 3

使用setCompoundDrawables()而不是 setCompoundDrawablesWithIntrinsicBounds() - 您必须手动设置可绘制对象的边界。