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

Dev*_*gur 6 android bitmap android-drawable

我需要在选项卡布局中的选项卡中将图像设置在文本上方.所以我在TextView使用setCompoundDrawablesWithIntrinsicBounds 设置图像,但我不知道如何给我的图像大小.

我试着给这样大小:

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

但它给了我这个错误:

Cannot resolve method setCompoundDrawablesWithIntrinsicBounds(int,android.graphics.drawable.Drawable,int,int);
Run Code Online (Sandbox Code Playgroud)

我也试过了

tabOne.setCompoundDrawables(0,mobile_drawable,0,0);
Run Code Online (Sandbox Code Playgroud)

但它也不起作用?

那么在使用setCompoundDrawablesWithIntrinsicBounds时如何给出图像大小?

Ano*_*p M 6

看一下这个

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

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


Fan*_*ing 6

接受的答案已过时且有问题...

您不能使用设置可绘制大小 setCompoundDrawablesWithIntrinsicBounds

相反,您需要setCompoundDrawables像这样设置它

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