总感觉上一篇文章说的太过于简洁,无法阐明我对TabHost的理解。下面我用一张自己的画的图,来讲述我对TabHost的理解。
话不多说,上图:
还记得我们AddTab的时候,参数是一个TabSpec吗? 好吧,我们来稍微了解一下TabSpec,这个类实在是非常简单,以至于我对于它甚至觉得没有什么可讲解的。
public class TabSpec {
private String mTag;
private IndicatorStrategy mIndicatorStrategy;
private ContentStrategy mContentStrategy;
private TabSpec(String tag) {
mTag = tag;
}
/**
* Specify a label as the tab indicator.
*/
public TabSpec setIndicator(CharSequence label) {
mIndicatorStrategy = new LabelIndicatorStrategy(label);
return this;
}
/**
* Specify a label and icon as the tab indicator.
*/
public TabSpec setIndicator(CharSequence label, Drawable icon) {
mIndicatorStrategy = new LabelAndIconIndicatorStrategy(label, icon);
return this;
}
/**
* Specify a view as the tab indicator.
*/
public TabSpec setIndicator(View view) {
mIndicatorStrategy = new ViewIndicatorStrategy(view);
return this;
}
/**
* Specify the id of the view that should be used as the content
* of the tab.
*/
public TabSpec setContent(int viewId) {
mContentStrategy = new ViewIdContentStrategy(viewId);
return this;
}
/**
* Specify a {@link android.widget.TabHost.TabContentFactory} to use to
* create the content of the tab.
*/
public TabSpec setContent(TabContentFactory contentFactory) {
mContentStrategy = new FactoryContentStrategy(mTag, contentFactory);
return this;
}
/**
* Specify an intent to use to launch an activity as the tab content.
*/
public TabSpec setContent(Intent intent) {
mContentStrategy = new IntentContentStrategy(mTag, intent);
return this;
}
public String getTag() {
return mTag;
}
}
相信对设计模式有所的了解的人一下就看出来了,
IndicatorStrategy mIndicatorStrategy;
ContentStrategy mContentStrategy;
正是两个策略接口,它们的意图是创建Indicator和Content的View以及如何Close这个View。而TabSpec正是承载这一切的一个实体类。
继续看上一篇文章,这回再结合图来看addTab这个函数,是不是有些清晰了呢?
public void addTab(TabSpec tabSpec) {
......
//得到你创建的IndicatorView
View tabIndicator = tabSpec.mIndicatorStrategy.createIndicatorView();
//在TabWidget(线性布局)中加入你所创建的IndicatorView
mTabWidget.addView(tabIndicator);
mTabSpecs.add(tabSpec);
if (mCurrentTab == -1) {
setCurrentTab(0);
}
}
这样,你所创建的TabSpec就变成Tab的模样显示在了View中。TabHost 的源码应该不难理解,我所阐述的不一定非常正确,希望大家还是多看看源码。经过这两篇文章,我相信自定义TabHost的布局应该没有任何难度了吧。