Problems with icon_drawable in navegation Drawable

2019-09-06 20:34发布

问题:

I am trying to show Icon_drawble in a ActionBar, but when R.drawable.ic_drawer is in the first position show return arrow in actionbar.

like this:

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_open, 
                R.string.drawer_close

                ) { 

I need to show something like this, but the code above It doesnt work.

If I change R.drawable.ic_drawer to another position,it give me the follow logcat error.

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerToggle = new ActionBarDrawerToggle(
                this,
                mDrawerLayout,

                R.string.drawer_open,
                R.drawable.ic_drawer,//another position
                R.string.drawer_close 

                ) 

Logcat:

java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.navegatiodrawer/com.example.navegatiodrawer.MainActivity}: android.content.res.Resources$NotFoundException: File Open navigation drawer from drawable resource ID

回答1:

This appears to be a bug in recent versions of the AppCompat library.

Part of the confusion is likely due to the fact that Android Studio's new project wizard generates bad code when you create a new navigation drawer activity- it uses the v4 support library ActionBarDrawerToggle, which is deprecated. Instead, it should use the v7 support library ActionBarDrawerToggle.

You have two options:

  • The best option is to switch to the v7 ActionBarDrawerToggle. To do this, change your imports to use android.support.v7.app.ActionBarDrawerToggle instead of android.support.v4.app.ActionBarDrawerToggle. The only other change you should need to make is removing your ic_drawer parameter altogether- the newer version of the toggle generates the hamburger you are looking for automatically.

  • If you insist on using the v4 toggle or a custom icon, you can revert to an older version of the support library. Using the default generated project when creating a new navigation drawer activity, I was able to sidestep this bug by reverting to com.android.support:appcompat-v7:22.1.0 in my build.gradle.

There is already a bug in the issue tracker for updating the wizard-generated code. I wouldn't expect the v4 toggle to get fixed since it is deprecated.