10

我想让我的用户通过单击应用程序图标来打开导航抽屉。这是我的代码:

@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);

}

但是当我点击图标时,什么也没有发生。问题出在哪里。

4

2 回答 2

22

在这里查看文档示例。您需要额外的代码

  • onPostCreate()同步您的抽屉状态
  • 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);
    }
    
    }
    
于 2013-11-10T12:14:50.617 回答
17

您应该覆盖onOptionsItemSelected活动并使用它:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
}
于 2013-11-10T12:05:11.743 回答