@斯坦的解決方案並沒有爲我工作,所以這裏是我的方式來實現對動作條的頂子菜單(但低於當然的主菜單):
我已創建2個xml文件:menu_main。XML和menu_more.xml位於在res /菜單目錄
第一個 'menu_main.xml' 包含菜單:
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- our addMenu doesn't have sub-items-->
<item
android:id="@+id/action_add"
android:icon="@drawable/ic_note_add_white_24dp"
android:title="@string/action_add"
app:showAsAction="ifRoom"/>
<!-- our moreMenu which show drop-down menu when clicked-->
<item
android:id="@+id/action_more"
android:icon="@drawable/ic_more_vert_white_24dp"
android:title="@string/action_more" <!--in text: "more"-->
app:showAsAction="always"/>
</menu>
,第二個「menu_more.xml '包含下拉菜單:
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- This menu will be hidden by default-->
<!-- But will be visible when moreMenu with '@+id/action_more' is clicked-->
<item
android:id="@+id/action_settings"
app:showAsAction="ifRoom|withText"
android:title="@string/action_settings" <!-- In text: "Settings"-->
android:visible="true"/>
</menu>
這是以前的我新加坡國立大學的樣子:
result-after-add-2-xmls(我沒有足夠的信譽10來顯示圖像)
在活動中,我重寫了這個方法:
公共布爾onPrepareOptionsMenu(菜單菜單)
在前面的方法中,我得到了對主菜單項的引用(在這種情況下是菜單@ + id/action_more位於m enu_main.xml文件),然後設置setOnMenuItemClickListener就可以了,最後,聲明併成立了的PopupMenu實例來管理和顯示子菜單項:
// show popup menu when menuMore clicked
menu.findItem(R.id.action_more).setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item)
{
// get reference to menuMore item
View menuMore = findViewById(item.getItemId());
// create a popup anchored to the view (menuMore)
// notes: if declare and set up PopupMenu Outside of this onMenuItemClick()
// then it'll not work!
// Because: the view you put into PopupMenu() could be null
final PopupMenu popupMenu = new PopupMenu(getApplicationContext(), menuMore);
// inflate 'menu_more.xml' layout file
// which contain all sub-items of menu
popupMenu.getMenuInflater().inflate(R.menu.menu_more, popupMenu.getMenu());
// process popup clicks on sub-items
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener()
{
@Override
public boolean onMenuItemClick(MenuItem item)
{
switch(item.getItemId()){
case R.id.action_settings:
Toast.makeText(getApplicationContext(), "showing SettingsActivity..",
Toast.LENGTH_SHORT).show();
break;
// more items go here
}
return true;
}
});
popupMenu.show();
return true;
}
});
return super.onPrepareOptionsMenu(menu);
這裏是最終結果:
final-look-drop-down-menu
想通了嗎? – JackyBoi 2015-04-17 13:44:46
同樣的問題在這裏(Android 5.1)。在Android開發過程中,經過幾年來這些「特性」的磕磕絆絆,我必須說Android是令人沮喪的平臺,唉。 – Stan 2015-05-26 12:13:00