如何将ActionBar中的Logo左对齐?求解决默认居中问题方案
解决Toolbar Logo左对齐的问题
嘿,我之前也碰到过这个Toolbar Logo居中的坑!试试下面这几个方案,应该能帮你搞定:
先提个小细节
你在toolbar_main.xml和ActivityHome.java里都设置了Logo,建议只保留一处,避免属性冲突~
方案一:自定义Toolbar布局(最稳妥灵活)
直接在Toolbar内部嵌套布局,手动控制Logo的位置,这是最不容易出问题的方法:
修改toolbar_main.xml:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"> <LinearLayout android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center_vertical" android:orientation="horizontal"> <!-- 左对齐的Logo,可根据需求调整边距 --> <ImageView android:id="@+id/toolbar_logo" android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/cookme_logo" android:layout_marginLeft="16dp"/> <!-- 自定义标题(如果需要),也可以保留Toolbar默认标题,去掉这个TextView即可 --> <TextView android:id="@+id/toolbar_title" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="@string/app_name" android:textColor="@android:color/white" android:textSize="18sp" android:layout_marginLeft="16dp"/> </LinearLayout> </android.support.v7.widget.Toolbar>
然后在ActivityHome.java里隐藏默认标题(如果用了自定义标题的话):
Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); // 隐藏Toolbar默认标题,使用自定义的TextView getSupportActionBar().setDisplayShowTitleEnabled(false);
方案二:通过代码调整Toolbar内部Logo的布局参数
如果不想改布局,可以遍历Toolbar的子View,找到Logo对应的ImageView,修改它的对齐方式:
Toolbar toolbar = findViewById(R.id.toolbar); setSupportActionBar(toolbar); toolbar.setLogo(R.drawable.cookme_logo); // 遍历Toolbar子View,找到Logo控件 for (int i = 0; i < toolbar.getChildCount(); i++) { View child = toolbar.getChildAt(i); // 通过contentDescription判断是否为Logo if (child instanceof ImageView && child.getContentDescription().equals(toolbar.getLogoDescription())) { Toolbar.LayoutParams params = new Toolbar.LayoutParams( Toolbar.LayoutParams.WRAP_CONTENT, Toolbar.LayoutParams.WRAP_CONTENT, Gravity.LEFT | Gravity.CENTER_VERTICAL ); params.leftMargin = 16; // 调整左边距,和系统风格匹配 ((ImageView) child).setLayoutParams(params); break; } }
方案三:修改Toolbar的内边距属性
Toolbar默认有contentInsetStart的内边距,导致Logo看起来居中,我们可以直接去掉这个内边距:
在styles.xml里定义自定义Toolbar样式(或者直接在布局里设置):
<style name="CustomToolbar" parent="Widget.AppCompat.Toolbar"> <item name="contentInsetStart">0dp</item> <item name="contentInsetLeft">0dp</item> </style>
然后在toolbar_main.xml中引用该样式:
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" app:style="@style/CustomToolbar" android:logo="@drawable/cookme_logo">
总结
个人最推荐方案一,自定义布局的方式完全由你控制元素位置,不会受系统默认样式的限制,适配性也更好。
内容的提问来源于stack exchange,提问作者Grace
相关产品推荐
相关产品推荐

