TabLayout.Tab设置文字+icon

TabLayout.Tab设置文字+icon

字数355  阅读537  评论0 

TabLayout是Google新出的一个控件,可以通过以下方式添加TabLayout.Tab

mTabLayout.addTab(mTabLayout.newTab().setText("Tab1"));
mTabLayout.addTab(mTabLayout.newTab().setText("Tab2"));

可如果Tab中既有文字,又有icon,且icon需要Tab的状态而改变,就比较麻烦了。我们可以使用SpannableString结合ImageSpan来实现。

    /**
     * 获取第三个tab的内容,其本质是把文字与icon结合在一起
     *
     * @param title 第三个tab栏需要显示的内容
     * @return
     */
    public CharSequence getThirdTabTitle(String title) {
        Drawable image = getResources().getDrawable(R.drawable.bg_down_arrow);
        image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
        // Replace blank spaces with image icon
        SpannableString sb = new SpannableString(title + "   ");
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
        sb.setSpan(imageSpan, title.length(), title.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        return sb;
    }

这样可以获取Tab需要显示的文本内容,进而通过setText (CharSequence text)方法设置显示内容。
或者根据不同的点击状态,直接设置Tab

    /**
     * 设置第三个tab的内容
     *
     * @param isTabSelected 第三个tab是否被点击
     */
    public void setThirdTab(boolean isTabSelected) {
        String title = "";
        //根据此时的tradingType来设置第三个tab栏的文字
        if (tradingType == -1) {
            title = "分类";
        } else {
            title = content[tradingType];
        }
        Drawable image;
        //根据第三个tab栏是否点击,设置不同的箭头方向
        if (isTabSelected) {
            image = getResources().getDrawable(R.drawable.down_arrow_press);
        } else {
            image = getResources().getDrawable(R.drawable.down_arrow_normal);
        }
        image.setBounds(0, 0, image.getIntrinsicWidth(), image.getIntrinsicHeight());
        // Replace blank spaces with image icon
        SpannableString sb = new SpannableString(title + "   ");
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BOTTOM);
        sb.setSpan(imageSpan, title.length(), title.length() + 1, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
        mTabLayout.getTabAt(2).setText(sb);
    }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值