10

When I am add icon like below:

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

enter image description here enter image description here

The icon resizes EditText. How can I calculate img size and put it into EditText without EditText resize?

Thanks!


FunkTheMonk
Use setCompounDrawables() instead of setCompoundDrawablesWithIntrinsicBounds() - you'll have to set the bounds of the drawables manually.

I don't understand how to calculate Bounds manually. I have got height and width of 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 );

but I have different results in different screen sizes. How I can calculate correct size and padding of icon? Could you please help me?

SLaks
  • 868,454
  • 176
  • 1,908
  • 1,964
IgorOK
  • 1,652
  • 4
  • 18
  • 36

3 Answers3

8

I think you can use different size of pics for different screens and use getMinimumWidth to set Bounds.But I did not try it before , may be it is not appropriate for .9 patch.

When you use setCompoundDrawables , you need code like :

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); 
Wangchao0721
  • 909
  • 1
  • 9
  • 23
5

I've found the solution in this post.

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

Community
  • 1
  • 1
Milton
  • 928
  • 1
  • 10
  • 22
  • 'java.lang.ClassCastException: android.graphics.drawable.VectorDrawable cannot be cast to android.graphics.drawable.BitmapDrawable' I am getting this error can you please tell me where i am wrong? – Nicks Jun 20 '17 at 08:19
  • @sumitmehra you should ask a separate question to get an answer. You were getting this error because you were loading an SVG as bitmap drawable. – vanomart Oct 31 '17 at 09:32
3

Use setCompoundDrawables() instead of setCompoundDrawablesWithIntrinsicBounds() - you'll have to set the bounds of the drawables manually.

Uli Köhler
  • 13,012
  • 16
  • 70
  • 120
FunkTheMonk
  • 10,908
  • 1
  • 31
  • 37