3

I have been stuck on this for days. I have an activity. I implemented

@Override
public void onBackPressed() {
    Log.e("TEST", "Pressed back");
    mAdapter.back();

}

The layout is a view pager and I have a FragmentStatePagerAdapter I extended managing it. I have tabs and I wanted to manage their history , so I implemented history logic as explained in https://stackoverflow.com/a/17832632/3821037 . It works fine but for some reason after I click to change a tab and hit on the android back button the first time I click isn't register - it doesn't call the activity OnBackPressed. The second call works fine. Does anyone know where the first event goes to? I should say that I never leave that same activity. I can also see the first event logged

05-20 12:44:17.952: I/ViewRootImpl(22749): ViewRoot's KeyEvent { action=ACTION_DOWN, keyCode=KEYCODE_BACK, scanCode=0, metaState=0, flags=0x48, repeatCount=0, eventTime=8406029, downTime=8406029, deviceId=-1, source=0x101 } to com.android.internal.policy.impl.PhoneWindow$DecorView{428bba20 V.E..... R....... 0,0-1080,1776}

Yet I'm not sure which object gets it (I also tried to add a listener on the view of the fragment and the viewPager, and also all the parents of the activity's root view - nothing is receiving it).

Thank you.

Community
  • 1
  • 1
yaronbic
  • 282
  • 1
  • 14

1 Answers1

0

The problem is that when you save history to the stack each time, you are adding that int value of the page you're going to. When you hit the back button, you are seeing it use the onBackPressed() but do nothing because it is popping/navigating the history addition of the tab that you currently on.

When you go from tab 2 to 3. Tab 3 is added to the stack.

If you hit the back button in this scenario, you will navigate to the last page added to the stack and remove it at the same time.

So you hit the back button expecting to navigate to tab at 2. The thing is, three was the last one added to the stack, so you navigate to 3 and remove it even though you're already on 3. The next onBackPressed() you navigate to 2 and remove it like expected.

Instead of using:

if (!pageHistory.empty()) {
   viewPager.setCurrentItem(pageHistory.pop().intValue());
}

try:

if (pageHistory.size()>1){
    pageHistory.pop().intValue();
    viewPager.setCurrentItem(pageHistory.peek());
}