Drawer Layout not closing on back pressed (dependi

2019-02-11 22:54发布

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;
        }
    }
}

8条回答
甜甜的少女心
2楼-- · 2019-02-11 23:21

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

查看更多
家丑人穷心不美
3楼-- · 2019-02-11 23:26

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();
}
查看更多
时光不老,我们不散
4楼-- · 2019-02-11 23:27

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

查看更多
ら.Afraid
5楼-- · 2019-02-11 23:35

In setUpNavDrawer

mDrawerLayout.setDescendantFocusability(ViewGroup.FOCUS_BLOCK_DESCENDANTS);

Also

@Override
public void onBackPressed()
{
  if (mDrawerLayout.isOpen())
    mDrawerLayout.close();
  else
    super.onBackPressed();
}
查看更多
何必那么认真
6楼-- · 2019-02-11 23:35

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 */

    ....
}
查看更多
霸刀☆藐视天下
7楼-- · 2019-02-11 23:40

Works without any warnings

@Override
public void onBackPressed() {
    if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
        drawerLayout.closeDrawer(GravityCompat.START);
    } else {
        super.onBackPressed();
    }
}
查看更多
登录 后发表回答