Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change tab index of fragments with tabs programmatically

I'm getting a null pointer exception when trying to switch tabs programmatically of a tablayout inside a fragment,

So I have my main activity that has a tab layout (4 tabs) each tab has a view pager holding a fragment, and each of these fragments has a tab layout (x amount of tabs) with a view pager holding a fragment, i can switch the tabs of my main activity tab layout from any fragment like this

TabLayout tabLayout = MainActivity.tabLayout;
TabLayout.Tab tab = tabLayout.getTabAt(2);
tab.select();

but if i try to change the tabs of one of the fragments in the same way i get a null pointer

TabLayout tabLayout2 = tabFragOne.tabLayout;
TabLayout.Tab tab2 = tabLayout2.getTabAt(2);
tab2.select();

it only happens if I click the button in question when the app first opens, which suggests that the reason for it is that the fragment hasn't been attached or created yet,

for instance if i scroll across to the fragments tab i want to switch to, and then go back to the main activity and press the button in question it will work. does anyone know the best way to fix this?

Ok ive found half the crux to this question is actually that im using a view pager adapter, a question here sheds a lot of light on my issue

like image 817
Martin Seal Avatar asked Jul 28 '16 16:07

Martin Seal


1 Answers

The correct way to set selected Tab, we should set selected index from Pager instead.

final ViewPager pager = (ViewPager) findViewById(R.id.pager);
final TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

tabLayout.setupWithViewPager(pager);
pager.setCurrentItem(0);//selected position

Here is my layout design in 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>
like image 87
THANN Phearum Avatar answered Sep 30 '22 13:09

THANN Phearum