Search code examples
androidandroid-fragmentsposition

Fragment position value, Using TabLayout and ViewPager


I made 4 Fragments which are contained TabLayout and ViewPager. And when I click tab, I want to see position value. so I used "Log.d".

But it isn't same what I think. In my case, when I click second tab (its position value is "1"), Log.d shows "1". But Log.d shows another value like "2" or "3". And a value which Log.d shows is not always same when I click same tab.

For example, I click first tab and click second tab later, position Log.d shows "2". But I click third or fourth tab, and click second tab later, position Log.d shows another value like "3" or "1". I'm very confused. What's the problem?

Here is my code.

(I'm sorry that I have poor English skill ^^;)

@Override
public Fragment getItem(int position){

    switch (position){
        case 0:
            Fragment1 fragment1 = new Fragment1();
            Log.d("Location", "0 Location " + position);
            return fragment1;
        case 1:
            Fragment2 fragment2 = new Fragment2();
            Log.d("Location", "1 Location " + position);
            return fragment2;
        case 2:
            Fragment3 fragment3 = new Fragment3();
            Log.d("Location", "2 Location " + position);
            return fragment3;
        case 3:
            Fragment4 fragment4 = new Fragment4();
            Log.d("Location", "3 Location는 " + position);
            return fragment4;
        default:
            return null;
    }

}

Solution

  • The Viewpager can be very confusing sometimes. When you are on the first fragment, the Viewpager will load the adjacent fragments into the memory.

    If you are on the first page, the Viewpager will load the second fragment as well. Similarly, when you are on the second fragment, the Viewpager loads the third fragment.

    If you are using Viewpager and you want to get the current fragment, you can get it by using the following code:

    int page = viewpager.getCurrentItem();