所以我的应用程序中有带有 Pager
的 TabLayout
,我认为它使用正确,但我有一个小问题:
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
为什么有空?
当我将 pager
中的 page
更改为第二个并单击按钮时,我得到了
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
又是null?到底是怎么回事?我花了几个小时试图理解这个问题,不确定发生了什么。
有什么想法吗?
最佳答案
Why is there a null?
因为ViewPager
还没有设置第三个页面。 ViewPager
此时不需要第三个子项,因为您只能向一个方向滑动。
No, null why?
因为 ViewPager
现在有三个页面,因为您可以双向滑动。
I think that should be default behaviour independent of selected tab
显然,ViewPager
的开发人员不同意您的观点。
And null again? What is going on?
ViewPager
此时不需要第三个子元素,因为您只能向一个方向滑动。
ViewPager
如何管理其子级是 ViewPager
内部实现的一部分。任何人都不应该依赖 ViewPager
对于 child 的任何特定行为。 IOW,停止在 ViewPager
上调用 getChildAt()
并期待特定结果。如果您想在特定页面上使用小部件,请让该页面的 Fragment
执行此操作,因为该 Fragment
可以直接访问其自己的小部件。
关于java - 为什么 TabLayout 总是打乱 Tab 键顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59214066/