Android系统自带的Menu布局有自己的间距,有时候不会满足GUI的要求,需要对某个图标进行细微的调整,目前只有对自定义的菜单图标进行单独的自定义,具体代码如下:
在Activity中初始化的ActionMode方法中设置:
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = new MenuInflater(this);
//将"全选"的菜单按钮初始化于ToolBar上
inflater.inflate(R.menu.menu_for_edit, menu);
//获取"全选"的菜单按钮
MenuItem menuItem_select = menu.findItem(R.id.menu_select_all);
//将对应的菜单按钮设置点击事件
menuItem_select.getActionView().setOnClickListener(v -> {
menu.performIdentifierAction(menuItem_select.getItemId(),0);
});
return true;
}
点击事件的监听实现:
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.menu_select_all:
//完成自己的逻辑即可
doSomething();
break;
default:
break;
}
return false;
}
自定义菜单(menu菜单项--R.menu.menu_for_edit)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<!--设置自定义的布局R.layout.menu_allselect_layout-->
<item
android:id="@+id/menu_select_all"
android:actionLayout="@layout/menu_allselect_layout"
android:title="@string/label_selectAll" />
</menu>
自定义布局(菜单的引用R.layout.menu_allselect_layout)的布局
其中,在对应的ImageView中设置对应的paddingRight值即可
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/dialer_menu_select_img"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingRight="20dp"
android:src="@drawable/ic_selection_all" />
</LinearLayout>
以上基本可以解决单个MenuItem偏移量的问题,如果需求Menu的布局与原生系统差异性太大的,就需要整体在Toolbar中使用自定义布局,不建议使用Menu系统菜单样式;
网友评论