The easiest way I found using icons is to use Tablayout.Tab.setIcon (drawable). It also makes it easier to highlight the selected icon. If you want to do this, follow these steps.
Step 1. Add your images to the res.mipmap folders. (mipmap-mdpi, hdpi, etc.) Judging by the other answers here, it is also great to put then in the res.drawable folders.
Step 2. Call setIcon on all tabs after setting TabLayout and ViewPager. I did this in my AdapterTabs to keep the activity in order. Therefore, in your activity, do the following:
tablayout = (TabLayout) findViewById(R.id.tab_layout); viewPager = (ViewPager) findViewById(R.id.viewPager); adapterTabs = new AdapterTabs(this, getSupportFragmentManager(), fragments, tablayout, viewPager); viewPager.setAdapter(adapterTabs); tablayout.setupWithViewPager(viewPager); adapterTabs.setTabIcons();
and in your AdapterTabs, which should extend the FragmentPagerAdapter, put your setTabIcons () method.
public void setTabTitlesToIcons() { Drawable icon1 = context.getResources().getDrawable(R.mipmap.ic_1); Drawable icon2 = context.getResources().getDrawable(R.mipmap.ic_2); Drawable icon3 = context.getResources().getDrawable(R.mipmap.ic_3); Drawable icon1Hilighted = context.getResources().getDrawable(R.mipmap.ic_1_selected); Drawable icon2Hilighted = context.getResources().getDrawable(R.mipmap.ic_2_selected); Drawable icon3Hilighted = context.getResources().getDrawable(R.mipmap.ic_3_selected); icons.add(icon1); icons.add(icon2); icons.add(icon3); iconsHilighted.add(icon1Hilighted); iconsHilighted.add(icon2Hilighted); iconsHilighted.add(icon3Hilighted); for(int i = 0; i < icons.size(); i++) { if(i == 0) {
Be sure to save the link to the icons of the two lists and the "Yellow" icons. You will need them later. Also keep a link to the TabLayout and ViewPager that you passed from the action.
Step 3. Verify that AdapterTabs.getPageTitle () returns null. At this point, if you run it, you will see that the first icon is highlighted.
Step 4. Deploy ViewPager.OnPageChangeListener in AdapterTabs and add this listener to your viewPager
public AdapterTabs(Context context, FragmentManager fragmentManager, List<Fragment> fragments, TabLayout tabLayout, ViewPager viewPager) { super(fragmentManager); this.context = context; this.tabLayout = tabLayout; this.viewPager = viewPager; this.viewPager.addOnPageChangeListener(this); tabs.add(fragments.get(0)); tabs.add(fragments.get(1)); tabs.add(fragments.get(2)); }
Step 5. Update the tabbed icons in the onPageSelected callback in AdapterTabs.
@Override public void onPageSelected(int position) { for (int i = 0; i < tabs.size(); i++) { if(i == position) {
You should now see an updated image when you change the tabs.