[英]Open navigation drawer by clicking the app icon
我想通過單擊應用程序圖標讓我的用戶打開導航欄。 這是我的代碼:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add);
// Show the Up button in the action bar.
DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.left_drawer);
ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
getActionBar().setTitle(R.string.title_activity_add);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(R.string.drawer_title);
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
getActionBar().setDisplayHomeAsUpEnabled(true); // Pressing the app icon in the action bar will navigate to the parent activity.
getActionBar().setHomeButtonEnabled(true);
}
但是當我點擊圖標時,沒有任何反應。 問題出在哪兒。
看看這里的文檔示例 。 你需要額外的代碼
onPostCreate()
用於同步您的Drawer狀態 onOptionsItemSelected()
用於處理App圖標的觸摸事件 onConfigurationChanged()
為抽屜提供新配置
public class YourActivity extends Activity { public ActionBarDrawerToggle mDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { ... mDrawerToggle = new ActionBarDrawerToggle(); ... } @Override protected void onPostCreate(Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); // Sync the toggle state after onRestoreInstanceState has occurred. mDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mDrawerToggle.onConfigurationChanged(newConfig); } @Override public boolean onOptionsItemSelected(MenuItem item) { // Pass the event to ActionBarDrawerToggle, if it returns // true, then it has handled the app icon touch event if (mDrawerToggle.onOptionsItemSelected(item)) { return true; } // Handle your other action bar items... return super.onOptionsItemSelected(item); } }
您應該覆蓋活動的onOptionsItemSelected
並使用:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.