使用 setCompoundDrawablesWithIntrinsicBounds() 方法时如何设置图像大小?

10
我需要将图片设置在选项卡中的文字上方,因此我使用setCompoundDrawablesWithIntrinsicBounds在我的TextView中设置图像,但我不知道如何为我的图像设置大小。
我尝试像这样指定大小:
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);

但它给我返回这个错误:

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

我也尝试过

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

但它还是不起作用?

那么,在使用setCompoundDrawablesWithIntrinsicBounds时如何指定图像大小呢?


1
可能是 Set drawable size programmatically 的重复问题。 - Vega
3个回答

11

1
“getDrawable”已被弃用......我们可以使用img = ContextCompat.getDrawable(MainActivity.this, R.drawable.mobile_icon);代替res.getDrawable - Devendra Dagur
最后一行中的 img_off 是什么? - Nicks
@AnoopM 请删除 Resources res = getResources(); 这一行,并将 img_off 替换为 img - user924

8

被接受的答案已经过时并且有缺陷...

你无法使用setCompoundDrawablesWithIntrinsicBounds设置可绘制对象大小。

相反,你需要使用setCompoundDrawables像这样设置:

Drawable img = ContextCompat.getDrawable(yourContext, R.drawable.yourImgId);
img.setBounds(0, 0, yourSize, yourSize);
yourTextView.setCompoundDrawables(img, null, null, null);

仅供您澄清 - 我查看了编辑历史记录。自“2015年11月5日7:27”起,已在被接受的答案中使用了“setCompoundDrawables”。谢谢。 - Stella

0

在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);

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