自定义Toolbar:如何将图标与标题设置为居中显示
解决Toolbar图标与标题居中的问题
嘿,我来帮你搞定这个Toolbar居中的问题!你之前尝试用RelativeLayout没成功,大概率是没处理好Toolbar的默认内边距,或者布局约束没设置对。下面给你两种靠谱的实现方案:
方案一:用ConstraintLayout实现(推荐)
ConstraintLayout的约束能力更灵活,能精准控制图标和标题的位置,代码如下:
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?actionBarSize" android:background="@color/colorPrimary" <!-- 必须去掉Toolbar默认的左边内边距,否则内容会偏右 --> android:contentInsetStart="0dp" app:contentInsetLeft="0dp"> <androidx.constraintlayout.widget.ConstraintLayout android:layout_width="match_parent" android:layout_height="match_parent"> <!-- 居中的图标 --> <ImageView android:id="@+id/toolbar_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_your_icon" app:layout_constraintStart_toStartOf="parent" app:layout_constraintEnd_toStartOf="@id/toolbar_title" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent" android:layout_marginEnd="8dp"/> <!-- 居中的标题 --> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="你的居中标题" android:textColor="@android:color/white" android:textSize="18sp" app:layout_constraintStart_toEndOf="@id/toolbar_icon" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:layout_constraintBottom_toBottomOf="parent"/> </androidx.constraintlayout.widget.ConstraintLayout> </androidx.appcompat.widget.Toolbar>
关键说明:
- 我加了
android:contentInsetStart="0dp"和app:contentInsetLeft="0dp",这是为了消除Toolbar默认的左边内边距(默认是为了适配返回键),不然你的图标和标题会莫名偏右。 - 通过ConstraintLayout的约束,把图标和标题绑定成一个整体,让它们在Toolbar里水平、垂直都居中。
方案二:用RelativeLayout实现
如果你坚持想用RelativeLayout,调整一下布局属性就行,代码如下:
<androidx.appcompat.widget.Toolbar android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?actionBarSize" android:background="@color/colorPrimary" android:contentInsetStart="0dp" app:contentInsetLeft="0dp"> <RelativeLayout android:layout_width="match_parent" android:layout_height="match_parent" <!-- 让RelativeLayout内部的内容整体居中 --> android:gravity="center_horizontal|center_vertical"> <ImageView android:id="@+id/toolbar_icon" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/ic_your_icon" android:layout_toStartOf="@id/toolbar_title" android:layout_marginEnd="8dp"/> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="你的居中标题" android:textColor="@android:color/white" android:textSize="18sp"/> </RelativeLayout> </androidx.appcompat.widget.Toolbar>
关键说明:
- 同样要去掉Toolbar的默认内边距,这点非常重要!
- 给RelativeLayout设置
android:gravity="center_horizontal|center_vertical",让内部的图标和标题作为一个整体居中显示,同时用layout_toStartOf把图标放在标题左边,保持两者的关联。
如果你的项目还在用旧的android.support.v7.widget.Toolbar,把上面代码里的androidx.appcompat.widget.Toolbar替换成它就行,属性都是通用的。
内容的提问来源于stack exchange,提问作者Krishna
相关产品推荐
相关产品推荐

