title: How to handle onBackPressed() in multiple fragment
body: <p>I am Android beginner, I am developing an app in which I have used multiple fragments through an activity.</p>
  
  <pre><code>private void displaySelectedScreen(int itemId) {
          Fragment fragment = null;
          switch (itemId) {
  
              case R.id.nav_home:
                  fragment = new HomeFragment();
                  break;
  
              case R.id.nav_attendance:
                  fragment = new AttendanceFragment();
                  break;
  
              case R.id.nav_notification:
                  fragment = new NotificationFragment();
                  break;
  
              case R.id.nav_event:
                 fragment = new EventFragment();
                  break;
  
              case R.id.nav_fee:
                 fragment = new FeesFragment();
                  break;
  
              case R.id.nav_news:
                  fragment = new NewsFragment();
                  break;
  
          }
          if (fragment != null) {
              FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
              ft.replace(R.id.frame_container, fragment);
              ft.addToBackStack(null);
              ft.commit();
          }
  
          DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
          drawer.closeDrawer(GravityCompat.START);
  
      }
  </code></pre>
  
  <p>and use an <code>onBackPressed()</code> method to close an app if the drawer is already close. Now I want to close an app if current fragment is <code>HomeFragment</code> and if current fragment is not <code>HomeFragment</code> then replace by <code>HomeFragment</code>. I don't know, how it does?</p>
  
  <pre><code>public void onBackPressed() {
      DrawerLayout drawer = (DrawerLayout)findViewById(R.id.drawer_layout);
      if (drawer.isDrawerOpen(GravityCompat.START)) {
          drawer.closeDrawer(GravityCompat.START);
      } else {
          closeApp();
      }
  }
  </code></pre>