我正在尝试采用v21 AppCompat库,并使用工具栏更好地控制ActionBar,如here和here所述。但无论我如何修改菜单XML,我都只能在溢出区域显示菜单项。我希望看到MenuItem在工具栏/ ActionBar上表示为一个图标。
我的菜单声明如下(请注意showAsAction行):
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:res-auto="http:/>/schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item android:id="@+id/action_add"
android:icon="@android:drawable/ic_menu_add"
android:title="@string/action_add"
android:orderInCategory="2"
res-auto:showAsAction="always" />
</menu>
我也试过这个(showAsAction行略有不同):
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:res-auto="http:/>/schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity" >
<item android:id="@+id/action_add"
android:icon="@android:drawable/ic_menu_add"
android:title="@string/action_add"
android:orderInCategory="2"
android:showAsAction="always" />
</menu>
但是我成功地将图标显示在工具栏/ ActionBar上的唯一方法是在代码中强制它。
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
// Try to manually force the item onto the bar instead of allowing it in the overflow
// for some reason, android is not picking up the setting in the menu declaration
// using android:showAsAction="always" (even when using the auto-res namespace)
MenuItem addItem = menu.findItem(R.id.action_add);
MenuCompat.setShowAsAction(addItem, MenuItem.SHOW_AS_ACTION_ALWAYS);
return true;
}
我使用android.support.v4.view.MenuCompat静态方法来实现这一点。但我相信我应该能够在XML中以声明方式执行此操作。我尝试过使用“always”和“ifRoom”,但没有效果。我只能假设没有选择XML属性。
我想这真的很简单,或者与我使用新工具栏作为菜单持有者的事实有关。工具栏布局非常简单:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:minHeight="?attr/actionBarSize"
android:background="?attr/colorPrimary" />
,用法似乎很标准:
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
任何帮助将不胜感激。我很乐意分享更多的项目内容,如果它有助于深入了解它。