How do I get the back button to go to a certain Fragment in horizontal scrolling? Exits app right now

倾然丶 夕夏残阳落幕 提交于 2019-12-06 12:09:31

If you use the ViewPager from your question which I answered earlier and you want to come back to the first fragment of the ViewPager when the user presses the BACK button then override the onBackPressed method like this:

@Override
public void onBackPressed() {
    if (getSupportFragmentManager().findFragmentByTag("outDialog") != null
            && ((DialogFragment) getSupportFragmentManager()
                    .findFragmentByTag("outDialog")).isVisible()) {
        // we have the out dialog visible and the user clicked back so let
        // the
        // normal events happen
        super.onBackPressed();
        return;
    }
    int currentPosition = mViewPager.getCurrentItem();
    if (currentPosition != 0) {
        // if the page the ViewPager shows isn't the first one then move it
        // to the first one
        mViewPager.setCurrentItem(0);
    } else {
        // we are at the first position already and the user wants out, so
        // annoy him with a dialog that asks him once again if he wants out.
        DialogFragment askHim = new DialogFragment();
        askHim.show(getSupportFragmentManager(), "outDialog");
        // in the dialog listener, if the user presses ok, finish the activity
    }
}

did you try to override Activity.onBackPressed() ? I used addToBackStack() and it works well, but I have no idea whether it works with PagerAdapter. I think you can override Activity.onBackPressed() and in that method, you can check whether current page is front page or not and do whatever job you want to do.

Here are pseudo code that I think.

public void onBackPressed() {
  if( pager.getCurrentPage() == 0 ) { //I'm not sure this method exists or not. just example. :-)
      //exit code here
  } else {
      // show first page
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!