我制作了4个包含TabLayout和ViewPager的片段。当我单击选项卡时,我希望看到位置值。所以我用了"Log.d“。
但这和我想的不一样。在我的示例中,当我单击第二个选项卡(其位置值为"1")时,Log.d显示"1“。但是Log.d显示了另一个类似于"2“或"3”的值。当我单击相同的选项卡时,Log.d显示的值并不总是相同的。
例如,我单击第一个选项卡,然后单击第二个选项卡,LocationLog.d显示"2“。但我单击第三个或第四个选项卡,然后单击第二个选项卡,LocationLog.d显示另一个类似于"3“或"1”的值。我很困惑。有什么问题吗?
这是我的密码。
(对不起,我的英语能力很差^^;)
@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;
}
}发布于 2018-02-21 07:39:21
查看器有时会非常令人困惑。当您在第一个片段上时,查看器将将相邻的片段加载到内存中。
如果您在第一个页面上,查看器也将加载第二个片段。类似地,当您在第二个片段上时,Viewpager将加载第三个片段。
如果您正在使用Viewpager,并且希望获得当前片段,则可以使用以下代码获得它:
int page = viewpager.getCurrentItem();发布于 2018-02-21 07:40:47
在PagerAdapter、PagerFragmentAdapter和PagerFragmentStateAdapter中,Views或Fragments是由密钥Object识别的,而不是由适配器中的index或position识别的。
显示什么视图不重要。当用户从第1页滑动到第2页时,ViewPager将加载第3页的视图,以期待下一次用户的滑动。
https://stackoverflow.com/questions/48900229
复制相似问题