为什么 TabLayout 总是弄乱 Tab 键顺序?



所以我在我的应用程序中TabLayoutPager,我认为它使用正确,但我有一点问题:

TabLayout.Tab asd1 = tabLayout.newTab().setText("Tab one");
TabLayout.Tab asd2 = tabLayout.newTab().setText("Tab two");
TabLayout.Tab asd3 = tabLayout.newTab().setText("Tab three");
tabLayout.addTab(asd1);
tabLayout.addTab(asd2);
tabLayout.addTab(asd3); 
pager = findViewById(R.id.pager);
InspectionRecordPager adapter = new InspectionRecordPager(getSupportFragmentManager(), tabLayout.getTabCount());
pager.setAdapter(adapter);

我的寻呼机没什么特别的,看起来像这样

public class InspectionRecordPager extends FragmentStatePagerAdapter {
private int tabCount;
public InspectionRecordPager(FragmentManager fm, int tabCount) {
super(fm);
this.tabCount = tabCount;
}
@Override
public Fragment getItem(int i) {
switch (i){
case 0:
return new Fragment1();
case 1:
return new Fragment2();
case 2:
return new Fragment3();
default:
return null;
}
}
@Override
public int getCount() {
return tabCount;
}

我还有设置onClickListener的按钮,我正在做这样的事情

button.addOnClickListener(new OnClickListener() {
public void onClick(View v){
Log.wtf("PAGER", pager.getChildAt(0) + " " + pager.getChildAt(1) + " " + pager.getChildAt(2));
}
}

当我运行应用程序并按下按钮时,我得到:

E/PAGER: android.widget.TableLayout{e83b671 V.E...... ........ 1200,0-2400,1265 #7f090031 app:id/frag_one} android.widget.TableLayout{7c15d8c V.E...... ........ 2400,0-3600,1265 #7f0900b6 app:id/frag_two} null

为什么存在空值?

当我将pagepager更改为秒并单击按钮时,我得到了

E/PAGER: android.widget.TableLayout{4915c18 V.E...... ........ 0,0-1200,1265 #7f09003e app:id/frag_one} android.widget.TableLayout{e83b671 V.E...... ........ 1200,0-2400,1265 #7f090031 app:id/frag_two} android.widget.TableLayout{7c15d8c V.E...... ......ID 2400,0-3600,1265 #7f0900b6 app:id/frag_three}

不,为什么?我认为这应该是独立于所选选项卡的默认行为。 而且当我选择第三个选项卡并按下按钮时,输出上发生了一些非常奇怪的事情

E/PAGER: android.widget.TableLayout{691c2a9 V.E...... ........ 1200,0-2400,1265 #7f090031 app:id/frag_two} android.widget.TableLayout{d15902e V.E...... ........ 2400,0-3600,1265 #7f0900b6 app:id/frag_three} null

又空了?这是怎么回事?我试图了解这个问题几个小时了,不确定发生了什么。

有什么想法吗?

为什么会有空值?

因为ViewPager还没有设置第三页。 此时ViewPager不需要第三个孩子,因为您只能向一个方向滑动。

不,为什么?

因为ViewPager现在有三个页面,因为您可以向两个方向滑动。

我认为这应该是独立于所选选项卡的默认行为

显然,ViewPager的开发人员不同意您的看法。

又空了?这是怎么回事?

此时ViewPager不需要第三个孩子,因为您只能向一个方向滑动。

ViewPager如何管理其孩子是ViewPager内部实施的一部分。任何人都不应该依赖ViewPager对儿童的任何特定行为。IOW,停止在ViewPager上调用getChildAt()并期待特定结果。如果您想在特定页面上使用小部件,请让该页面的Fragment执行此操作,因为该Fragment可以直接访问自己的小部件。

最新更新