要实现这一点,您需要实现一个自定义 TabHost,它会覆盖 Android 框架中的 TabHost。
public class CustomTabHost extends TabHost {
public CustomTabHost(Context context) {
super(context);
}
public CustomTabHost(Context context, AttributeSet attrs) {
super(context, attrs);
}
}
Androids TabHost 有一个名为TabSpec 的内部类,它实现了以下方法:
public TabSpec setIndicator(CharSequence label, Drawable icon) {
mIndicatorStrategy = new LabelAndIconIndicatorStrategy(label, icon);
return this;
}
所以为了添加另一个TextView到Tab,你需要像这样重载这个方法:
public TabSpec setIndicator(CharSequence label, Drawable icon, CharSequence text) {
mIndicatorStrategy = new LabelIconTextIndicatorStrategy(label, icon, text);
return this;
}
要完成这项工作,您还需要实现一个类似于LabelAndIconIndicatorStrategy 的LabelIconTextIndicatorStrategy,但包含一个文本。
private class LabelIconTextIndicatorStrategy implements IndicatorStrategy {
private final CharSequence mLabel;
private final Drawable mIcon;
private final CharSequence mText;
private LabelIconTextIndicatorStrategy(CharSequence label, Drawable icon, CharSequence text) {
mLabel = label;
mIcon = icon;
mText = text;
}
public View createIndicatorView() {
final Context context = getContext();
LayoutInflater inflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View tabIndicator = inflater.inflate(mTabLayoutId,
mTabWidget, // tab widget is the parent
false); // no inflate params
final TextView tv = (TextView) tabIndicator.findViewById(R.id.title);
final ImageView iconView = (ImageView) tabIndicator.findViewById(R.id.icon);
// when icon is gone by default, we're in exclusive mode
final boolean exclusive = iconView.getVisibility() == View.GONE;
final boolean bindIcon = !exclusive || TextUtils.isEmpty(mLabel);
tv.setText(mLabel);
if (bindIcon && mIcon != null) {
iconView.setImageDrawable(mIcon);
iconView.setVisibility(VISIBLE);
}
if (context.getApplicationInfo().targetSdkVersion <= Build.VERSION_CODES.DONUT) {
// Donut apps get old color scheme
tabIndicator.setBackgroundResource(R.drawable.tab_indicator_v4);
tv.setTextColor(context.getResources().getColorStateList(R.color.tab_indicator_text_v4));
}
return tabIndicator;
}
}