简体   繁体   中英

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;
    }

}

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();

In PagerAdapter , PagerFragmentAdapter and PagerFragmentStateAdapter , the Views or Fragments are recognised by a key Object not by their index or position in the adapter.

It shouldn't matter what view is displaying. When user swipes from page 1 to page 2, ViewPager loads the view for page 3 in anticipation of the next user swipe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM