4

I have successfully determined that to change the icon in the NavDrawer between the hamburger and arrow, this code needs to be toggled:

mDrawerToggle.syncState();

However, when I click the back button it is still opening the navigation drawer when indeed I want to return to the previous activity.

I know I could simply set an onClickListener, but I figured Android had a more native way of navigating to the previous screen. Here is my code:'

onCreate:

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle(
            this,                  /* host Activity */
            mDrawerLayout,         /* DrawerLayout object */
            toolbar,  /* nav drawer icon to replace 'Up' caret */
            R.string.drawer_open,  /* "open drawer" description */
            R.string.drawer_close  /* "close drawer" description */
    ) {

        /**
         * Called when a drawer has settled in a completely closed state.
         */
        public void onDrawerClosed(View view) {
            super.onDrawerClosed(view);
            isOpen = false;
        }

        /**
         * Called when a drawer has settled in a completely open state.
         */
        public void onDrawerOpened(View drawerView) {
            super.onDrawerOpened(drawerView);
            isOpen = true;
        }
    };
    mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onBackPressed();
        }
    });
    mDrawerToggle.setDrawerIndicatorEnabled(false);
    mDrawerLayout.addDrawerListener(mDrawerToggle);

    mDrawerList = (ListView) findViewById(R.id.left_drawer);
    ArrayList<String> drawerTitleArray = new ArrayList<>();
    drawerTitleArray.add(0, "TEST");
    drawerTitleArray.add(1, "TEST 1");
    // Set the adapter for the list view
    mDrawerList.setAdapter(new ArrayAdapter<String>(this,
            R.layout.drawer_list_item, drawerTitleArray));


       // TODO: Add Fragment Code to check if savedInstanceState ==                                 null; add at Activity Level?
    // Check that the activity is using the layout version with
    // the fragment_container FrameLayout


    //set up viewpager for current day
    //mPager = (ViewPager)               findViewById(R.id.home_polls_viewpager_fragment_container);
    //mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
    //mPager.setAdapter(mPagerAdapter);


    //get current date to apply to Viewpager
    mDateFormat = new SimpleDateFormat("MM-dd-yyyy");
    mDate = new Date();
    mCurrentDateString = mDateFormat.format(mDate);
    mViewPager = (ViewPager) findViewById(R.id.poll_fragment_container);
    mViewPager.setAdapter(new SectionPagerAdapter(getSupportFragmentManager()));
    mTabLayout.setupWithViewPager(mViewPager);

    // TODO: Checkn if AuthStateListenerNecessary
    //Determine whether necessary to use an AuthStateListener here
    // mUserRef.addAuthStateListener(new Firebase.AuthStateListener() {
    //@Override
    //public void onAuthStateChanged(AuthData authData) {
    //if (authData == null) {
    //Intent backToSignIn = new Intent(getApplication(),       SignupActivity.class);
    //startActivity(backToSignIn);
    //                    finish();
    //                }
    //            }
    //        })




}

@Override
protected void onStart() {
    super.onStart();

    v = new ValueEventListener() {
        //testing methodology of adding children
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            int pollsAvailable = (int) dataSnapshot.child(mCurrentDateString).getChildrenCount();
       //                mPagerAdapter.setPollsAvailable(pollsAvailable);
            Log.i("TAG", "There are " + String.valueOf(pollsAvailable) + " children in today's poll count.");
        }

        @Override
        public void onCancelled(FirebaseError firebaseError) {

        }
    };

    mPollsRef.addValueEventListener(v);

}

@Override
protected void onStop() {
    super.onStop();
    mPollsRef.removeEventListener(v);

}

@Override
public void onFragmentInteraction(Uri uri) {

}

@Override
public boolean onOptionsItemSelected(MenuItem item){
    if (item.getItemId() == android.R.id.home){
        super.onBackPressed();
        return true;}
    else
        return mDrawerToggle.onOptionsItemSelected(item) || super.onOptionsItemSelected(item);
}



@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    //TODO: Be sure to only allow one instance of each activity
    //TODO:Address mDrawerToggle code from StackOverflow to make sure I am correctly implementing the return to previous activity
    // Sync the toggle state after onRestoreInstanceState has occurred.
    //        mDrawerToggle.syncState();
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mDrawerToggle.onConfigurationChanged(newConfig);
}

public class SectionPagerAdapter extends FragmentPagerAdapter {

    public SectionPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        int pollIndex = mIntentFromTouch.getIntExtra("Poll_Index",0);
        switch (position) {
            case 0:
                PollFragment pollFragment = PollFragment.newInstance(pollIndex);
                return pollFragment;
            case 1:
                DiscussionFragment discussionFragment = DiscussionFragment.newInstance(pollIndex);
                return discussionFragment;
            default:
                return new PollFragment();
        }
    }

    @Override
    public int getCount() {
        return 2;
    }

    @Override
    public CharSequence getPageTitle(int position) {
        switch (position) {
            case 0:
                return getResources().getString(R.string.poll_text);
            case 1:
                return getResources().getString(R.string.discussion_text);
            default:
                return getResources().getString(R.string.poll_text);
        }
      }
   }


 }
tccpg288
  • 3,242
  • 5
  • 35
  • 80

1 Answers1

2

Actually, the syncState() method ensures that the toggle's image is in a matching state with the drawer, and sets the image on the Toolbar/ActionBar. It doesn't toggle the drawer/back functionality.

The setDrawerIndicatorEnabled() method is what you're looking for. When the indicator is enabled, the toggle operates the drawer. When it is disabled, it falls back on the navigation OnClickListener, if you've set one.

To handle the back functionality, add the following to the toggle's setup:

mDrawerToggle.setHomeAsUpIndicator(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
mDrawerToggle.setToolbarNavigationClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            onBackPressed();
        }
    }
);

Then, when you want to disable the drawer operation, and allow clicking the toggle to go back, simply call:

mDrawerToggle.setDrawerIndicatorEnabled(false);

I would also point out that, since you've used the ActionBarDrawerToggle constructor that takes a Toolbar argument, the Activity's onOptionsItemSelected() method will not be called when clicking the toggle, and the mDrawerToggle.onOptionsItemSelected(item) call isn't needed there.


NB: Depending on the support library version you're using, the back arrow Drawable resource might be named R.drawable.abc_ic_ab_back_material instead. Please refer to this post for more information.

Community
  • 1
  • 1
Mike M.
  • 38,532
  • 8
  • 99
  • 95
  • Thanks! I will give it a shot. Is that drawable included in the Android SDK? – tccpg288 Jul 26 '16 at 01:36
  • It's included in the support library. – Mike M. Jul 26 '16 at 01:37
  • Oh, actually, depending on the library version, it might be under a different name: `R.drawable.abc_ic_ab_back_material`. Have a look at [this post](http://stackoverflow.com/questions/35632576/error-cannot-find-symbol-variable-abc-ic-ab-back-mtrl-am-alpha). I'll amend my answer here in a minute. – Mike M. Jul 26 '16 at 01:38
  • Just to clarify, should I have the syncState() method implemented? Or does it recognize that I am not using the state of the NavDrawer? – tccpg288 Jul 26 '16 at 13:41
  • How do you mean "not using the state of the NavDrawer", exactly? Are you not using the toggle to operate the drawer at all? That is, are you only opening/closing the drawer by dragging? – Mike M. Jul 26 '16 at 13:45
  • I have actually updated my code (see above) and the back button arrow shows and navigates to the previous screen. In other words, it is functioning properly, however I do not believe I followed your instructions completely. Can you let me know if there are issues with the way I have set up the back arrow? – tccpg288 Jul 26 '16 at 23:12
  • Yeah, that's just fine, as long as it works for you. Depending on the rest of your setup, you might not need to set that drawable at all. I just included it as a catchall. It seems, though, that you don't need an `ActionBarDrawerToggle` at all, however, since you're immediately disabling the indicator. That's why I was asking in my previous comment. An `ActionBarDrawerToggle` is meant specifically to control the drawer. If you only want to use the drawer by dragging, you don't need the toggle. You can just directly setup that button to go back. – Mike M. Jul 26 '16 at 23:21
  • I do want to use the toggle and the slide, and both are working correctly right now. I appreciate your help – tccpg288 Jul 26 '16 at 23:26
  • Ah, OK, then you should be good to go. Just use the `setDrawerIndicatorEnabled()` method to switch between the drawer and the back button. Btw, it really looks like you don't need the `onOptionsItemSelected()` method at all. It's not going to fire from clicking the toggle, 'cause of the particular `ActionBarDrawerToggle` constructor you're using. When using a `Toolbar` with that, it takes care of everything internally. Just a note. Glad it works for ya. Cheers! – Mike M. Jul 26 '16 at 23:32