TabLayout是Google新出的一個控件,可以通過以下方式添加TabLayout.Tab。
mTabLayout.addTab(mTabLayout.newTab().setText("Tab1"));
mTabLayout.addTab(mTabLayout.newTab().setText("Tab2"));
可如果Tab中既有文字,又有icon,且icon需要Tab的狀態(tài)而改變,就比較麻煩了。我們可以使用SpannableString結(jié)合ImageSpan來實現(xiàn)。
/**
* 獲取第三個tab的內(nèi)容,其本質(zhì)是把文字與icon結(jié)合在一起
*
* @param title 第三個tab欄需要顯示的內(nèi)容
* @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需要顯示的文本內(nèi)容,進而通過setText (CharSequence text)方法設(shè)置顯示內(nèi)容。
或者根據(jù)不同的點擊狀態(tài),直接設(shè)置Tab
/**
* 設(shè)置第三個tab的內(nèi)容
*
* @param isTabSelected 第三個tab是否被點擊
*/
public void setThirdTab(boolean isTabSelected) {
String title = "";
//根據(jù)此時的tradingType來設(shè)置第三個tab欄的文字
if (tradingType == -1) {
title = "分類";
} else {
title = content[tradingType];
}
Drawable image;
//根據(jù)第三個tab欄是否點擊,設(shè)置不同的箭頭方向
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);
}