7

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

Community
  • 1
  • 1
Martin Seal
  • 616
  • 2
  • 14
  • 32

7 Answers7

4

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>
THANN Phearum
  • 1,969
  • 22
  • 19
  • when i use this the text doesnt highlight like it should, or like it does using getTabAt – Martin Seal Aug 06 '16 at 20:13
  • @MartinSeal, I am not sure about your case, but I think your TabLayout design in xml missing some configuration. I have added my example of my TabLayout in xml design. Please check. – THANN Phearum Aug 08 '16 at 01:44
1
TabLayout tabhost = (TabLayout) getActivity().findViewById(R.id.tabLayout);
tabhost.getTabAt(2).select();

I use this inside my fragment's create function... and it works perfectly R.id.tabLayout is the tablayout id in your main activity layout.

succcubbus
  • 874
  • 1
  • 7
  • 24
NimaGhasri
  • 41
  • 5
0

Try this:

 TabLayout tablayout;
      @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main); //your activity layout
            tabLayout =(TabLayout)findViewById(R.id.tablayout); //your tab layout id
            tabLayout.getTabAt(0).select(); //your tab index;
    }
Vishal Thakkar
  • 652
  • 4
  • 18
  • this is what i currently do but as the fragment holding the other tab layout isnt attached yet i get a null pointer when trying to change its tab position, i can move the main activity tab no problems – Martin Seal Aug 06 '16 at 20:24
0

you can use the setCurrentItem(Postion) in viewpager example :

tabLayout.setOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(mViewPager));
// tabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(4);
0

Simple example to automatically scroll from the last page to the first. Note: I added a dummy fragment at the first and last position.

        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                if (position == 0) {
                    viewPager.setCurrentItem(viewPagerAdapter.getCount() - 2);
                } else if (position == viewPagerAdapter.getCount() - 1) {
                    viewPager.setCurrentItem(1);
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
Robin Dijkhof
  • 18,665
  • 11
  • 65
  • 116
  • this looks cool thank you, ive tried to implement it but because of where i need to call it i cant get viewPagerAdapter.getCount() from a static context – Martin Seal Aug 06 '16 at 20:26
0

Using view pager, Its working simple and fine

public class ViewPagerAdapter  extends FragmentStatePagerAdapter {

CharSequence Titles[]; // This will Store the Titles of the Tabs which are Going to be passed when ViewPagerAdapter is created
int NumbOfTabs;
String mode;
AllDeals deals;     
MyDeals myDeals;    those are my fragments


public ViewPagerAdapter(FragmentManager fm, int mNumbOfTabsumb, String moe) {
    super(fm);
    this.NumbOfTabs = mNumbOfTabsumb;
    mode=moe;
}

@Override
public Fragment getItem(int position) {

    switch (position) {
        case 0:
            if(mode.equals("Deals")){
                 deals=new AllDeals();
                return deals;
            } 
            break;

        case 1:

            if(mode.equals("Deals")){
                myDeals=new MyDeals();
                return myDeals;
            } 

           break;
        default:
            break;

    }
    return null;
}



@Override
public int getCount() {
    return NumbOfTabs;
}
 }

add this lines into ur activity

  containerViewone.setVisibility(View.VISIBLE);
   tabLayout.addTab(tabLayout.newTab().setText(getResources().getString(R.string.title_all_deals)));
                    tabLayout.addTab(tabLayout.newTab().setText(getResources().getString(R.string.title_my_deals)));
                    tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
                    tabLayout.setTabTextColors(getResources().getColor(R.color.tabunselect), getResources().getColor(R.color.black));
                    viewpagerad = new ViewPagerAdapter(getSupportFragmentManager(), Numboftabs, "Deals");
                     pager.setAdapter(viewpagerad);
                    pager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
0

In Kotlin: With TabLayout and ViewPager2 that works for me:

binding.tablayout.getTabAt(1)!!.select()
chrisu.chrisu
  • 119
  • 2
  • 14