为何无法通过toolbarStyle主题配置Toolbar的layout_height和layout_width?
为什么Toolbar主题样式里的layout_width/layout_height不生效?
这个问题我之前做项目的时候也踩过坑,核心原因其实很明确:layout_width和layout_height属于布局参数(LayoutParams),这类属性是由父容器负责解析的,根本不属于toolbarStyle的可配置范围。
先搞懂为什么背景、文字颜色能生效
你主题里设置的android:background、android:titleTextColor这类属性,属于Toolbar自身的View样式属性,Android的主题样式系统会帮我们把这些属性应用到View实例上。而布局宽高不一样,它不是View自身的属性,是告诉父容器“我要占多大空间”的指令,只能在布局文件里设置,或者通过代码给View设置LayoutParams,没法通过主题样式传递。
怎么确认toolbarStyle的可配置范围?
你已经找到Toolbar的构造方法和toolbarStyle的属性定义,接下来可以通过这两种方式明确它能配置哪些属性:
- 查看AppCompat默认样式:打开Android SDK目录下的
appcompat/res/values/styles.xml,找到Widget.AppCompat.Toolbar的定义,里面列出来的所有属性都是toolbarStyle支持配置的。比如默认样式里包含android:minHeight(这是Toolbar自身的最小高度属性,不是布局高度)、titleTextAppearance、subtitleTextAppearance这些,完全看不到layout_width/layout_height的影子。 - 看Toolbar的属性解析逻辑:翻Toolbar的源码,会发现它在初始化时,从
toolbarStyle里读取的都是和自身UI相关的属性(比如标题样式、背景、导航图标等),根本不会去处理LayoutParams相关的属性——因为这是父布局的工作。
那怎么统一设置Toolbar的宽高?
如果不想每次写布局都重复写宽高,给你两个可行方案:
- 封装Toolbar布局:写一个单独的
layout_toolbar.xml,在里面固定好宽高和其他属性,然后在需要的布局里用<include>引入:<!-- layout_toolbar.xml --> <androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="@color/colorBackground" android:titleTextColor="@color/colorTextToolbar"/> - 自定义Toolbar类:在构造方法里默认设置LayoutParams,这样布局里直接用自定义类就不用写宽高了:
public class FixedToolbar extends androidx.appcompat.widget.Toolbar { public FixedToolbar(Context context) { this(context, null); } public FixedToolbar(Context context, AttributeSet attrs) { this(context, attrs, R.attr.toolbarStyle); } public FixedToolbar(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); LayoutParams params = new LayoutParams( LayoutParams.MATCH_PARENT, (int) getContext().getResources().getDimension(R.dimen.action_bar_size) ); setLayoutParams(params); } }
内容的提问来源于stack exchange,提问作者OuttaSpaceTime
相关产品推荐
相关产品推荐

