title: Kotlin - Handling Back Button Click in Navigation Drawer - Android
body: <p>I have implemented Navigation Drawer in android.</p>
  <p>Working fine.</p>
  <p>onBackPressed method is also implemented.</p>
  <p>Working fine.</p>
  <p>Now, I want same onBackPressed() method's functionality on Back Button click of Navigation Drawer. (Back Button is set in Navigation Drawer.)</p>
  <p>I have set Back Arrow button as below :</p>
  <pre><code>// Set back button
      mFragmentManager.addOnBackStackChangedListener(FragmentManager.OnBackStackChangedListener {
          if (mFragmentManager.backStackEntryCount &gt; 0) {
              supportActionBar!!.setDisplayHomeAsUpEnabled(true)
          } else {
              supportActionBar!!.setDisplayHomeAsUpEnabled(false)
              mToggle.syncState()
          }
      })
  </code></pre>
  <p>Now, to take the click of Back button I have implemented below method :</p>
  <pre><code>override fun onOptionsItemSelected(item: MenuItem): Boolean {
      when (item.itemId) {
          android.R.id.home-&gt; {
              Toast.makeText(this, &quot;Back pressed&quot;, Toast.LENGTH_SHORT)
                  .show();
              onBackPressed();
          }
      }
      return super.onOptionsItemSelected(item)
  }
  </code></pre>
  <p>But, this toast inside is not displaying, instead it just opening my Navigation Drawer.</p>
  <p>What might be the issue ? Thanks.</p>
  <p><strong>EDIT :</strong></p>
  <p>Below is the code to open Drawer i.e. as below :</p>
  <pre><code>mToggle = ActionBarDrawerToggle(
              this,
              mDrawer,
              toolbar,
              R.string.navigation_drawer_open,
              R.string.navigation_drawer_close
          )
          mDrawer.addDrawerListener(mToggle)
          mToggle.syncState()
  </code></pre>
  <p>Here, just set a ActionBarDrawerToggle to Navigation Drawer. So, Drawer open when I click on HumberIcon.</p>
  <p>Below is the onBackPressed() method inside my Activity :</p>
  <pre><code>if (mDrawer.isDrawerOpen(GravityCompat.START)) {
              mDrawer.closeDrawer(GravityCompat.START)
          } else {
              if (mFragmentManager.backStackEntryCount &gt; 0) {
                  mFragmentManager.popBackStack()
                  nav_view.setCheckedItem(R.id.nav_home_fragment)
                  
              } else {
                  if (mFragmentManager.findFragmentById(R.id.fragment_container) is SecondFragment) {
                      mFragmentManager.popBackStack()
                      nav_view.setCheckedItem(R.id.nav_home_fragment)
                  } else {
                      super.onBackPressed()
                  }
              }
          }
      }
  </code></pre>