我正在尝试使用自定义工具栏。我希望图标和标题位于工具栏的中心。我已经尝试了很多将其设置在中心但我无法做到这一点。我的 XML 如下所示
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?actionBarSize"
android:layout_width="match_parent"
android:background="@color/colorPrimary">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="horizontal">
<ImageView
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher"/>
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:gravity="center"
android:text="MyApplication"
android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:textColor="@color/colorWhite" />
</RelativeLayout>
</android.support.v7.widget.Toolbar>
但它的显示效果并不符合我的需要。我想要第一个 Logo 和标题位于工具栏中心,但它看起来像这样
如果有人可以帮助我,请告诉我。如果它很简单,我真的很抱歉。我还在学习。谢谢
最佳答案
试试这个:
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_height="?actionBarSize"
android:layout_width="match_parent"
android:paddingRight="16dp"
android:background="@color/colorPrimary">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="horizontal">
<ImageView
android:padding="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="@drawable/ic_launcher"/>
<TextView
android:id="@+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MyApplication"
android:textAppearance="@style/TextAppearance.Widget.AppCompat.Toolbar.Title"
android:textColor="@color/colorWhite" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
使用LinearLayout
可以让您轻松确保 View 不重叠。我还在右侧添加了 16dp 的内边距,以补偿 Android 自动添加到左侧的 16dp 边距。
关于java - 工具栏标题和图标位于中心,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49565157/