[英]How to open the navigation drawer when button clicks ? without using action bar in android
[英]How to hide action bar button in fragment when Navigation Drawer is open
我使用導航抽屜,對於其中一個片段,我有不同的菜單。 對於打開導航抽屜時的片段,如何隱藏操作欄的按鈕? 例如,在圖片( http://prntscr.com/7ur712 )上,它是刷新按鈕。
@Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
**setHasOptionsMenu(true);** }
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
super.onCreateOptionsMenu(menu, inflater);
**inflater.inflate(R.menu.my_menu, menu);**
}
實現ActionBarDrawerToogle以獲取導航抽屜的狀態。 調用invalidateOptionsMenu();
使菜單在導航抽屜的打開/關閉狀態下失效。
稍后根據狀態,您可以使用以下方法顯示/隱藏導航項:
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
// inflate menu from xml
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.settings, menu);
if (mState == MENU_HIDDEN)
{
for (int i = 0; i < menu.size(); i++)
menu.getItem(i).setVisible(false);
}
}
更新actionBar按鈕的最佳方法是在打開/關閉NavigationDrawer
時調用invalidateOptionsMenu()
。
根據Android培訓文檔頁面,在創建ActionBarDrawerToggle
,您應該覆蓋onDrawerClosed
和onDrawerOpened
方法:
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
R.drawable.ic_drawer, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getActionBar().setTitle(mTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getActionBar().setTitle(mDrawerTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
另外,在onPrepareOptionsMenu
方法中,您可以檢測抽屜是否打開,並加載與抽屜狀態相對應的菜單:
/* Called whenever we call invalidateOptionsMenu() */
@Override
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
有關更多信息,您可以在此處查看Android開發人員文檔: https : //developer.android.com/training/implementing-navigation/nav-drawer.html (參見部分:偵聽打開和關閉事件)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.