15

I'm following the Creating a Navigation Drawer tutorial (Android Training).

I have downloaded the sample app and it work as intended. I open the drawer, press back and it gets closed.

The problem comes when I replace the lib/android-support-v4.jar (originally with a size of 523 KB) with the updated version (revision 20) in my Android-SDK/extras/android/support/v4/android-support-v4.jar (with size 741 KB). After the replacement if I open the drawer and then press the back button of the device the app gets closed instead of closing the drawer.

How can I solve that? Should I keep the old android-support-v4.jar version or should I programmatically intercept the back button closing the drawer when needed?

UPDATE: I've continue testing the problem, to do so I built the project in AndroidStudio. After copy the sample app (src, res and update the manifest) ran it: The back button closes the app even if the DrawerLayout is open. Then I modified the build.gradle file changing the line:

compile 'com.android.support:appcompat-v7:20.0.0'

with

compile 'com.android.support:appcompat-v7:19.0.0'

And the problem disapeared: The back button first closes the drawer and then closes the app

Full code for the activity (Link to the Android Training Source Code):

public class MainActivity extends Activity {
    private DrawerLayout mDrawerLayout;
    private ListView mDrawerList;
    private ActionBarDrawerToggle mDrawerToggle;

    private CharSequence mDrawerTitle;
    private CharSequence mTitle;
    private String[] mPlanetTitles;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = mDrawerTitle = getTitle();
        mPlanetTitles = getResources().getStringArray(R.array.planets_array);
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.left_drawer);

        // set a custom shadow that overlays the main content when the drawer opens
        mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        // set up the drawer's list view with items and click listener
        mDrawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, mPlanetTitles));
        mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        // ActionBarDrawerToggle ties together the the proper interactions
        // between the sliding drawer and the action bar app icon
        mDrawerToggle = new ActionBarDrawerToggle(
                this,                  /* host Activity */
                mDrawerLayout,         /* DrawerLayout object */
                R.drawable.ic_drawer,  /* nav drawer image to replace 'Up' caret */
                R.string.drawer_open,  /* "open drawer" description for accessibility */
                R.string.drawer_close  /* "close drawer" description for accessibility */
                ) {
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                //supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }

            public void onDrawerOpened(View drawerView) {
                getActionBar().setTitle(mDrawerTitle);
                //supportInvalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
            }
        };
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        if (savedInstanceState == null) {
            selectItem(0);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.main, menu);
        return super.onCreateOptionsMenu(menu);
    }

    /* 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);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
         // The action bar home/up action should open or close the drawer.
         // ActionBarDrawerToggle will take care of this.
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        // Handle action buttons
        switch(item.getItemId()) {
        case R.id.action_websearch:
            // create intent to perform web search for this planet
            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
            intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
            // catch event that there's no activity to handle intent
            if (intent.resolveActivity(getPackageManager()) != null) {
                startActivity(intent);
            } else {
                Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
            }
            return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

    /* The click listner for ListView in the navigation drawer */
    private class DrawerItemClickListener implements ListView.OnItemClickListener {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            selectItem(position);
        }
    }

    private void selectItem(int position) {
        // update the main content by replacing fragments
        Fragment fragment = new PlanetFragment();
        Bundle args = new Bundle();
        args.putInt(PlanetFragment.ARG_PLANET_NUMBER, position);
        fragment.setArguments(args);

        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        // update selected item and title, then close the drawer
        mDrawerList.setItemChecked(position, true);
        setTitle(mPlanetTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
    }

    @Override
    public void setTitle(CharSequence title) {
        mTitle = title;
        getActionBar().setTitle(mTitle);
    }

    /**
     * When using the ActionBarDrawerToggle, you must call it during
     * onPostCreate() and onConfigurationChanged()...
     */

    @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);
        // Pass any configuration change to the drawer toggls
        mDrawerToggle.onConfigurationChanged(newConfig);
    }

    /**
     * Fragment that appears in the "content_frame", shows a planet
     */
    public static class PlanetFragment extends Fragment {
        public static final String ARG_PLANET_NUMBER = "planet_number";

        public PlanetFragment() {
            // Empty constructor required for fragment subclasses
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_planet, container, false);
            int i = getArguments().getInt(ARG_PLANET_NUMBER);
            String planet = getResources().getStringArray(R.array.planets_array)[i];

            int imageId = getResources().getIdentifier(planet.toLowerCase(Locale.getDefault()),
                            "drawable", getActivity().getPackageName());
            ((ImageView) rootView.findViewById(R.id.image)).setImageResource(imageId);
            getActivity().setTitle(planet);
            return rootView;
        }
    }
}
Addev
  • 31,819
  • 51
  • 183
  • 302

10 Answers10

23

I have the exactly same problem after upgrading the support library to 20.0.0.

Add below one line code can fix my problem. (onCreate in my activitiy)

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home);

    mDrawerLayout = (DrawerLayout) this.findViewById(R.id.drawer_layout);
    mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); /* add this line */

    ....
}
正宗白布鞋
  • 929
  • 6
  • 13
  • 1
    Test on support library v21 today, the same issue still exists, and same fix still works in my project. – 正宗白布鞋 Oct 18 '14 at 04:08
  • 3
    `mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);` prevents the keyboard to open when you have a EditView somewhere in your DrawerLayout hierarchy, since the EditView won't gain focus. – Gregor Koukkoullis Jan 29 '15 at 13:43
19

Here is a quick fix to your problem. Just override the onBackPressed() method in your Activity / Fragment :

@Override
public void onBackPressed()
{
    if (mDrawerLayout.isDrawerOpen(Gravity.START))
        mDrawerLayout.closeDrawer(Gravity.START);
    else
        super.onBackPressed();
}

Use Gravity.START for the left drawer, Gravity.END for the right one

MathieuMaree
  • 7,453
  • 6
  • 26
  • 31
  • I'm sure the support lib is the problem, in fact I can see how the problem disappearing and coming back just swapping between libraries – Addev Oct 06 '14 at 12:30
15

In setUpNavDrawer

mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

Also

@Override
public void onBackPressed()
{
  if (mDrawerLayout.isOpen())
    mDrawerLayout.close();
  else
    super.onBackPressed();
}
atiruz
  • 2,782
  • 27
  • 36
Danial Hussain
  • 2,488
  • 18
  • 38
  • 2
    It's worth noting that blocking focus on the descendants of the drawer will also block all other UI elements, even when the drawer is closed. This means all text entry is blocked once you've set this descendant focusability. – SDJMcHattie Mar 20 '15 at 13:24
  • 1
    As @SDJMcHattie said, if you have an edittext or any other view it will not react to focus. – frankelot Sep 02 '15 at 20:28
2

The solution with mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS); is not recommend because you can't gain focus if you have a TextEdit on the activity. Better use the onBackPressed() solution as it mentioned before.

@Override
public void onBackPressed()
{
  if (mDrawerLayout.isOpen())
    mDrawerLayout.close();
  else
    super.onBackPressed();
}
user3907002
  • 375
  • 1
  • 4
  • 17
1

right click on your project click properties and goto java build path and check if the libraries you want are there and there aint no unwanted libraries..also if you change the supportlibrary v4, i suggest you change it in appcompat v7 library.. secondly

onDrawerOpened

is when the drawerlayout is surfaced fully on your ui, if its not surfaced fully the activity is closed instead..

so kindly re-check these in your code from the documentation site

The main content view (the FrameLayout above) must be the first child in the 
DrawerLayout because the XML order implies z-ordering and the drawer must be 
on top of the content.
The main content view is set to match the parent view's width and height,
because it represents the entire UI when the navigation drawer is hidden.
The drawer view (the ListView) must specify its horizontal gravity with the 
android:layout_gravity attribute. To support right-to-left (RTL) languages,
specify the value with "start" instead of "left" (so the drawer appears on
the right when the layout is RTL).
The drawer view specifies its width in dp units and the height matches 
the parent view. The drawer width should be no more than 320dp so the
user can always see a portion of the main content.

lastly i see that you are using support library, and if you use support library you should not use activity you should use ActiobBarActivity or FragmentActivity

Elltz
  • 10,730
  • 4
  • 31
  • 59
1

Focus is an issue here, but its not actually children stealing the focus it's parents above the drawer layout (ActionBar/Toolbar).

I use a very similar method to this in my MainActivity.class:

@Override
public void onBackPressed() {
    if (mDrawerLayout.isDrawerVisible(Gravity.START)) {
        mDrawerLayout.closeDrawer(Gravity.START);
        return;
    }
    super.onBackPressed();
}
Chris.Jenkins
  • 13,051
  • 4
  • 60
  • 61
0

Try this fix:

mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BEFORE_DESCENDANTS);

...

mDrawerLayout.setDrawerListener(new DrawerListener() {

    @Override
    public void onDrawerStateChanged(int arg0) {

    }

    @Override
    public void onDrawerSlide(View arg0, float arg1) {

    }

    @Override
    public void onDrawerOpened(View view) {
        mDrawerLayout.post(new Runnable() {

            @Override
            public void run() {
                // request the focus to correctly process pressed
                // back key
                mDrawerLayout.requestFocus();
            }
        });
    }

    @Override
    public void onDrawerClosed(View arg0) {
    }
});
Eugene Popovich
  • 3,343
  • 2
  • 30
  • 33
0

Works without any warnings

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
Vlad
  • 7,997
  • 3
  • 56
  • 43
0

initialise this

  navigationView.setNavigationItemSelectedListener(this)
        actionBarToggle = ActionBarDrawerToggle(this, drawerLayout, 0, 0)
        drawerLayout.addDrawerListener(actionBarToggle)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        actionBarToggle.syncState()

then handle by using this method

override fun onSupportNavigateUp(): Boolean {
        if (this.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            this.drawerLayout.closeDrawer(GravityCompat.START)
        } else {
            this.drawerLayout.openDrawer(GravityCompat.START)
        }
        return true
    }
Navin Kumar
  • 3,393
  • 3
  • 21
  • 46
0

if you want to close the drawer onBackPressed() but the function is not even getting called when the back button is pressed and one more condition you are using latest version android 13 then you should try adding below code in your OnCreate() or whatever you want to use and for more android 13

val callback = onBackPressedDispatcher.addCallback(this, false) {
        drawerLayout.closeDrawer(GravityCompat.START)
    }

    drawerLayout.addDrawerListener(object : DrawerLayout.DrawerListener {

        override fun onDrawerOpened(drawerView: View) {
            callback.isEnabled = true
        }

        override fun onDrawerClosed(drawerView: View) {
            callback.isEnabled = false
        }

        override fun onDrawerSlide(drawerView: View, slideOffset: Float) = Unit
        override fun onDrawerStateChanged(newState: Int) = Unit
    })

you have to import view, drawerListener, callback

import androidx.activity.addCallback