关于TabLayout设置文字+图片时,图片显示不出来的问题。

来源:互联网 发布:淘宝怎么催客人下订单 编辑:程序博客网 时间:2024/04/29 08:17

首先,网上有“一种方法,通过SpannableString实现,如下:

public CharSequence getTitleWithIcon(String title) {
Drawable image = getResources().getDrawable(R.drawable.icon_arrow_down);
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;
}

实际证明,此种方法无效!!!!

正确解决方案:

tabLayout.addTab(tabLayout.newTab().setText(“精选”));
tabLayout.addTab(tabLayout.newTab().setText(“筛选”));

然后在Tablayout布局完成后,设置:

tabLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
tabLayout.getTabAt(1).setCustomView(R.layout.tab_qa_item);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
tabLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});

注意:适配器里面一定要重写:

@Override
public CharSequence getPageTitle(int position)

0 0
原创粉丝点击