AKronis1369 AKronis1369 - 5 months ago 17
Android Question

non-foreground tabs created when clicking on another tab

I developed an application that has three tabs and one activity that show these layouts. In total, I have 3 fragments.

I studied many tutorials and used them.
I have three fragment and each has the line

return inflater.inflate(R.layout.tab_fragment_*, container, false);


*1 or 2 or 3 according to which fragment.

I put a break point on this line but I saw something happening that I can't understand.

When I select tab1 in debug mode my debugger hits code in the fragment for tab2!!!!
Then it hits code in the fragment for tab1, and then it shows the right result. When I select tab2 the debuger hits code in the fragment for tab3!!!! Then it shows the right results. When I select tab3 my debugger doesn't hit any of break points but shows right results.

Help me please.

I see right things but I can not understand it. By this behavior I can not add some action on button click on each tab(fragment in this case).

one of my reference is :
http://www.truiton.com/2015/06/android-tabs-example-fragments-viewpager/

ALSO i used Android 2.2 API.

Answer

When using a lot of pages this would be horribly slow and even unnecessary if the user would never swipe through all these pages. By default the ViewPager only creates the current page as well as the offscreen pages to the left and right of the current page.

(See http://www.androidzeitgeist.com/2012/10/examining-viewpager-2.html)

When you click on tab1, fragment1 is created (to display to the user immediately) and so is fragment2 (to be ready to be scrolled onscreen at any moment). When you click on tab2, fragment2 already exists (see previous step) and is immediately displayed, fragment3 is created (to be ready to be scrolled onscreen).

You might be tempted to try to set the offscreen page limit to zero so (theoretically) each fragment is created only when it comes onscreen, but it won't work. The lowest the offscreen page limit can be is 1.

If you need to do something with a tab when it becomes selected, you might try something like this:

viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
  @Override
  public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

  }

  @Override public void onPageSelected(int position) {
    Fragment selectedFragment = fragments.get(position));
    //do something here
  }

  @Override public void onPageScrollStateChanged(int state) {

  }
});