当我尝试以编程方式切换 fragment 内 tablayout 的选项卡时出现空指针异常,
所以我的主要 Activity 有一个选项卡布局(4 个选项卡),每个选项卡都有一个包含 fragment 的 View 寻呼机,并且每个 fragment 都有一个选项卡布局(x 个选项卡)和一个包含 fragment 的 View 寻呼机, 我可以从这样的任何 fragment 切换我的主要 Activity 选项卡布局的选项卡
TabLayout tabLayout = MainActivity.tabLayout;
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();
但是如果我尝试以相同的方式更改其中一个 fragment 的选项卡,我会得到一个空指针
TabLayout tabLayout2 = tabFragOne.tabLayout;
TabLayout.Tab tab2 = tabLayout2.getTabAt(2);
tab2.select();
仅当我在应用程序首次打开时单击相关按钮时才会发生这种情况,这表明其原因是尚未附加或创建 fragment ,
例如,如果我滚动到我想切换到的 fragment 选项卡,然后返回到主要 Activity 并按下相关按钮,它将起作用。 有谁知道解决此问题的最佳方法?
我发现这个问题的一半症结实际上是我使用了一个 View 寻呼机适配器,一个问题 here阐明了我的问题
最佳答案
设置selected Tab的正确方法,我们应该从Pager设置selected index。
final ViewPager pager = (ViewPager) findViewById(R.id.pager);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);
tabLayout.setupWithViewPager(pager);
pager.setCurrentItem(0);//selected position
这是我在xml中的布局设计
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="#ffffff"
android:background="@color/al_white"
android:elevation="0dp" />
<android.support.design.widget.TabLayout
android:id="@+id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#ffffff"
app:tabTextColor="#494a43"
app:tabSelectedTextColor="#494a43"
app:tabIndicatorColor="#494a43"
app:tabIndicatorHeight="2dp"
app:tabMode="fixed"
app:tabGravity="fill" />
</android.support.design.widget.AppBarLayout>
关于android - 以编程方式使用选项卡更改 fragment 的选项卡索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38642314/