10

I need to set image above text in tabs in Tab Layout. So I set image in my TextView using setCompoundDrawablesWithIntrinsicBounds but I don't know how give size for my image.

I tried to give size like this:

Drawable dr = ContextCompat.getDrawable(MainActivity.this, R.drawable.mobile_icon);
    Bitmap bitmap = ((BitmapDrawable) dr).getBitmap();
    mobile_drawable = new BitmapDrawable(getResources(), Bitmap.createScaledBitmap(bitmap, 50, 50, true));

    TextView tabOne = (TextView) LayoutInflater.from(this).inflate(R.layout.custom_tab, null);
    tabOne.setText("Mobile");
    tabOne.setCompoundDrawablesWithIntrinsicBounds(0,mobile_drawable,0,0);
    tabLayout.getTabAt(0).setCustomView(tabOne);

But it gives me this error:

Cannot resolve method setCompoundDrawablesWithIntrinsicBounds(int,android.graphics.drawable.Drawable,int,int);

I also tried

tabOne.setCompoundDrawables(0,mobile_drawable,0,0);

but it also not working?

So how to give image size when using setCompoundDrawablesWithIntrinsicBounds???

Devendra Dagur
  • 840
  • 1
  • 14
  • 35
  • 1
    Possible duplicate of [Set drawable size programmatically](https://stackoverflow.com/questions/4609456/set-drawable-size-programmatically) – Vega Aug 30 '19 at 19:29

3 Answers3

11

Check this out

Drawable img = ContextCompat.getDrawable(MainActivity.this,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, null, null, null); 

Calculate image size when using setCompoundDrawables for EditText

Anoop M Maddasseri
  • 10,213
  • 3
  • 52
  • 73
8

The accepted answer is outdated and buggy...

You cannot set drawable size using setCompoundDrawablesWithIntrinsicBounds

Instead, you need to set it using setCompoundDrawables like this

Drawable img = ContextCompat.getDrawable(yourContext, R.drawable.yourImgId);
img.setBounds(0, 0, yourSize, yourSize);
yourTextView.setCompoundDrawables(img, null, null, null);
Community
  • 1
  • 1
Fangming
  • 24,551
  • 6
  • 100
  • 90
  • Just for your clarification - I went through the edit history. Since `Nov 5 '15 at 7:27` itself `setCompoundDrawables` used in the accepted answer. Thanks. – Stella May 07 '20 at 12:46
0

What worked for me in VS.Xamarin

text = parentView.FindViewById<EditText>(Resource.Id.text);
Drawable img = ContextCompat.getDrawable(context, R.id.resource_id);
img.SetBounds(0, 0, 20, 20); 
text.SetCompoundDrawables(img, null, null, null);
JaydeepW
  • 3,237
  • 1
  • 25
  • 27
Stefan Michev
  • 4,795
  • 3
  • 35
  • 30