在Android中为MenuItem添加边距
我试图在工具栏的右边创建一个文本菜单,左边距为16dp。有人知道如何通过添加以下代码来设置16dp余量吗在Android中为MenuItem添加边距,android,android-layout,Android,Android Layout,我试图在工具栏的右边创建一个文本菜单,左边距为16dp。有人知道如何通过添加以下代码来设置16dp余量吗 @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. final MenuItem menuItem = menu.add(Menu.NONE, 100, Menu.NO
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
final MenuItem menuItem = menu.add(Menu.NONE, 100, Menu.NONE, getString(R.string.menu_done));
MenuItemCompat.setShowAsAction(menuItem, MenuItem.SHOW_AS_ACTION_IF_ROOM);
return true;
}
使用java:
View view = new View(this);
menuItem.setActionView(view);
view.setPadding(16,0,0,0); //left , top ,right , bottom
或XML:
将此样式添加到工具栏中的图标
<style name="myToolbarStyle" parent="@style/Widget.AppCompat.Toolbar">
<item name="android:paddingLeft">16dp</item>
</style>
16dp
当然,如果您有更多的项目,您需要为该项目创建一个特定的样式,以便保留填充。由于@Lazai
我的实现
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
View view = new View(getApplicationContext());
view.setLayoutParams(new ViewGroup.LayoutParams(ViewUtil.dp2px(16),
ViewGroup.LayoutParams.MATCH_PARENT));
MenuItem space = menu.findItem(R.id.space);
space.setActionView(view);
//...
return true;
}
其中ViewUtil.dp2px(16)
是
@SuppressWarnings("unused")
public static int dp2px(int dp) {
float density = Resources.getSystem().getDisplayMetrics().density;
return Math.round(dp * density);
}
工作正常,不可点击但这将替换添加到菜单中的内容。我想你可以添加文本,甚至图标,但如果你想保持图标之间的顺序,我不这么认为。对不起,我想帮忙。