在选项卡中设置带文本的图标 Activity

Set Icon with Text in a Tabbed Activity

我正在尝试在 tabbed-activity 中实现一个带有文本的图标。我不明白如何可视化图标。

这是代码:

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;
    }

这是最终结果:

哪里错了?

这样试试,

    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