为何调整MaterialToolbar的AdaptiveIconDrawable图标大小无效?
解决MaterialToolbar设置Logo尺寸不生效的问题
直接修改AdaptiveIconDrawable的bounds无效,是因为MaterialToolbar在渲染Logo时,会根据自身的布局逻辑重新计算尺寸,忽略手动设置的bounds。以下是几种可行的解决方法:
方法一:自定义Drawable包裹原Logo,重写固有尺寸
创建一个自定义Drawable,包裹原AdaptiveIconDrawable,通过重写getIntrinsicWidth和getIntrinsicHeight来控制显示尺寸:
public class ScaledDrawable extends DrawableWrapper { private final float scaleFactor; public ScaledDrawable(Drawable drawable, float scaleFactor) { super(drawable); this.scaleFactor = scaleFactor; } @Override public int getIntrinsicWidth() { return (int) (super.getIntrinsicWidth() * scaleFactor); } @Override public int getIntrinsicHeight() { return (int) (super.getIntrinsicHeight() * scaleFactor); } }
在Activity中使用:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AdaptiveIconDrawable originalLogo = (AdaptiveIconDrawable) _toolbar.getLogo(); // 缩小到原尺寸的1/4 ScaledDrawable scaledLogo = new ScaledDrawable(originalLogo, 0.25f); _toolbar.setLogo(scaledLogo); }
方法二:直接调整Logo对应的ImageView尺寸
MaterialToolbar提供getLogoView()方法(需Material Components库版本足够新),可直接获取Logo的ImageView并设置宽高:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { ImageView logoView = _toolbar.getLogoView(); if (logoView != null) { ViewGroup.LayoutParams params = logoView.getLayoutParams(); // 示例:设置为40dp对应的像素值 int size = (int) getResources().getDimension(R.dimen.logo_size); params.width = size; params.height = size; logoView.setLayoutParams(params); } }
若getLogoView()不可用,可遍历Toolbar子View找到Logo对应的ImageView:
private ImageView findLogoView(Toolbar toolbar) { for (int i = 0; i < toolbar.getChildCount(); i++) { View child = toolbar.getChildAt(i); if (child instanceof ImageView && child.getContentDescription().equals(toolbar.getLogoDescription())) { return (ImageView) child; } } return null; }
方法三:将Logo转为Bitmap后缩小
把原AdaptiveIconDrawable转换成Bitmap,缩小后再转成Drawable设置给Toolbar:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { AdaptiveIconDrawable originalLogo = (AdaptiveIconDrawable) _toolbar.getLogo(); Bitmap originalBitmap = drawableToBitmap(originalLogo); // 缩小到原尺寸的1/4 Bitmap scaledBitmap = Bitmap.createScaledBitmap(originalBitmap, originalBitmap.getWidth() / 4, originalBitmap.getHeight() / 4, true); _toolbar.setLogo(new BitmapDrawable(getResources(), scaledBitmap)); originalBitmap.recycle(); } // 辅助方法:Drawable转Bitmap private Bitmap drawableToBitmap(Drawable drawable) { if (drawable instanceof BitmapDrawable) { return ((BitmapDrawable) drawable).getBitmap(); } Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); return bitmap; }
内容的提问来源于stack exchange,提问作者Hong
相关产品推荐
相关产品推荐

