Android ToolBar的meun自定义位置遇到的几个坑。
ToolBar弹出的meun默认位置是覆盖是覆盖在ToolBar上的。
需要自定义style toolbar的默认style是Widget.AppCompat.Light.PopupMenu.Overflow,所以我parent继承默认style对其进行修改。
<!--Toolbar弹出层样式 -->
<style name="OverflowMenuStyle" parent="@style/Widget.AppCompat.Light.PopupMenu.Overflow">
<!-- 是否覆盖锚点,默认为true,即盖住Toolbar -->
<item name="overlapAnchor">false</item>
<!-- 弹出层字体颜色 -->
<item name="android:textColorSecondary">@color/font_white</item>
<!-- 弹出层背景颜色 -->
<item name="android:colorBackground">@color/first_theme</item>
<!-- 弹出层水平方向上的偏移,即距离屏幕左边的距离,负值会导致右边出现空隙 -->
<item name="android:dropDownHorizontalOffset">-10dp</item>
<!-- 弹出层垂直方向距离toolbar的距离 -->
<item name="android:dropDownVerticalOffset">@dimen/woying_35_dip</item>
<item name="android:popupBackground">@color/bg_red</item>
</style>
然后使用toolbar时引用style
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar_stu"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:navigationIcon="@drawable/back_up"
app:popupTheme="@style/OverflowMenuStyle"
app:theme="@style/Toolbar"
app:titleTextAppearance="@style/Toolbar.TitleText"
/>
app:popupTheme="@style/OverflowMenuStyle"
app:theme="@style/Toolbar"
这个是toolbar的自定义style
其中overlapAnchor设为flase弹出的menu就不会覆盖toolbar。
但是我想修改下dropDownHorizontalOffset,dropDownVerticalOffset无论如何都不起作用,原来meun的style要被toolbar的style引用,才会起效果。
<style name="Toolbar" parent="Theme.AppCompat">
<item name="colorPrimary">@color/first_theme</item>
<item name="colorPrimaryDark">@color/first_theme</item>
<item name="colorAccent">@color/first_theme</item>
<!-- toolbar菜单文字尺寸 -->
<item name="actionMenuTextAppearance">@style/ToolbarMenuTextSize</item>
<!-- 加入toolbar溢出【弹出】菜单的风格 -->
<item name="actionOverflowMenuStyle">@style/OverflowMenuStyle</item>
</style>
到目前为止位置设置好了,但是还是有问题弹出来的meun出现了大黑边,查找好多资料发现是因为设置了下面个属性导致。
<item name="android:popupBackground">@color/bg_red</item>
把他去掉后就可以了,因为toolbar弹出来的menu是PopupWindow,看下面源码
<style name="Widget.Material.ListPopupWindow">
<item name="dropDownSelector">?attr/listChoiceBackgroundIndicator</item>
<item name="popupBackground">@drawable/popup_background_material</item>
<item name="popupElevation">@dimen/floating_window_z</item>
<item name="popupAnimationStyle">@empty</item>
<item name="popupEnterTransition">@transition/popup_window_enter</item>
<item name="popupExitTransition">@transition/popup_window_exit</item>
<item name="dropDownVerticalOffset">0dip</item>
<item name="dropDownHorizontalOffset">0dip</item>
<item name="dropDownWidth">wrap_content</item>
</style>
ListPopupWindow设置了背景属性弹出来会出现黑边,我测试是在5.0以上机器上会出现。