0

I'm trying to implement a icons with text in my tabbed-activity. I don't understand how to visualize the icons.

this is the code:

tab_layout.xml:

<android.support.design.widget.TabLayout
    android:id="@+id/tabs"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:tabMaxWidth="0dp"
    app:tabGravity="fill"
    app:tabMode="fixed">

tab.java:

private int[] imageResId = {
            R.drawable.ic_one,
            R.drawable.icona_storia,
            R.drawable.icona_piatti_tipici,
            R.drawable.icona_monumenti
    };

    private Context context;
    private String tabTitles[] = new String[] { "Meteo", "Locali", "InfoCittà", "Mappa" };

    @Override
    public CharSequence getPageTitle(int position){
        Drawable image = context.getResources().getDrawable(imageResId[position]);
        image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
        SpannableString sb = new SpannableString("   " + tabTitles[position]);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
        sb.setSpan(imageSpan, 0, 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }

This is the final result:

Where is the mistake?

KKKKK
  • 273
  • 2
  • 18

1 Answers1

1

Try like this,

    tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_home));
    tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_profile));
    tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_settings));

See more details here

Gobu CSG
  • 653
  • 5
  • 7
  • Thank you, but this can't resolve my problem, I want icons with alongside text, this option give me or just icons or just text – KKKKK Jun 25 '18 at 16:54
  • I tried tabLayout.addTab(tabLayout.newTab().setIcon(R.mipmap.ic_settings).setText("hello")); and now it looks good – KKKKK Jun 25 '18 at 17:00
  • Ok thank you, now it worked perfectly, so +1 deserved – KKKKK Jun 25 '18 at 17:14
  • but if I want the icon to the left of the text, how should I do it? – KKKKK Jun 25 '18 at 17:18
  • Now I have the icon and below the text, I would like to have both in the same line – KKKKK Jun 25 '18 at 17:26