When your setIcon
method called before the tabLayout
is setup with tabLayout.setupWithViewPager(viewPager);
, this will throw a null pointer exception in runtime.
To fix the run time error, you should call setupTabIcons()
after your tabLayout.setupWithViewPager(viewPager);
line in onCreate
method of the activity.
But this still shows the warning in android studio, so to remove the warning and also prevent run time error, you should change your code to get tab index instead of setting it manually such as 0,1,2 as in your .getTabAt(0)
, .getTabAt(1)
, .getTabAt(2)
parts
For the clearance, I will put an example from my code:
private TabAdapter tabAdapter;
private TabLayout tabLayout;
private ViewPager viewPager;
private int[] tabIcons = {
R.drawable.ic_action_profile,
R.drawable.ic_action_people,
R.drawable.ic_action_messages
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
viewPager = findViewById(R.id.viewPager);
tabLayout = findViewById(R.id.tabLayout);
// Create the adapter that will return a fragment for each of the two
// primary sections of the activity.
tabAdapter = new TabAdapter(getSupportFragmentManager());
tabAdapter.addFragment(new AccountFragment(), "Account");
tabAdapter.addFragment(new HomeFragment(), "People");
tabAdapter.addFragment(new CommunicateFragment(), "Messages");
viewPager.setAdapter(tabAdapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setupWithViewPager(viewPager);
for (int i=0; i<tabLayout.getTabCount();i++) {
tabLayout.getTabAt(i).setIcon(tabIcons[i]);
}
}
Note: Please make sure to have equal amount of icons in tabIcons
array as you are creating tabs.