1、TabWidget 的 layout文件
<?xml version="1.0" encoding="utf-8"?>
<TabHost xmlns:andro>
</TabWidget>
</LinearLayout>
</TabHost>
2、tab布局的layout文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:andro/>
</LinearLayout>
3、MainActivity
public class MainActivity extends TabActivity {
private static final String TAB_SALE = "SALE";
private static final String TAB_CART = "CART";
private static final String TAB_REPORT = "REPORT";
private static final String TAB_SETUP = "SETUP";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.maintabs);
TabHost tabHost = getTabHost();
//first tab
tabHost.addTab(tabHost.newTabSpec(TAB_SALE)
.setIndicator(prepareTabView(TAB_SALE))
.setContent(new Intent(this, SaleActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
//second tab
tabHost.addTab(tabHost.newTabSpec(TAB_CART)
.setIndicator(prepareTabView(TAB_CART))
.setContent(new Intent(this, CartActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
//third tab
tabHost.addTab(tabHost.newTabSpec(TAB_REPORT)
.setIndicator(prepareTabView(TAB_REPORT))
.setContent(new Intent(this, ReportActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
//forth tab
tabHost.addTab(tabHost.newTabSpec(TAB_SETUP)
.setIndicator(prepareTabView(TAB_SETUP))
.setContent(new Intent(this, SetupActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)));
tabHost.setCurrentTab(0);//设置当前的选项卡,这里为Tab1
}
//自定义 标签按钮
private View prepareTabView(String text) {
View view = LayoutInflater.from(this).inflate(R.layout.main_tab_view, null);
ImageView imageView = (ImageView) view.findViewById(R.id.tab_icon);
imageView.setBackground(getDrawable(text));
TextView textView = (TextView) view.findViewById(R.id.tab_text);
textView.setText(text);
return view;
}
private Drawable getDrawable(String tabLabel){
Drawable backgroundDrawable = null;
if (tabLabel.equals(TAB_SALE)) {
backgroundDrawable = getResources().getDrawable(R.drawable.tab_sale);
} else if (tabLabel.equals(TAB_CART)) {
backgroundDrawable = getResources().getDrawable(R.drawable.tab_cart);
} else if (tabLabel.equals(TAB_REPORT)) {
backgroundDrawable = getResources().getDrawable(R.drawable.tab_report);
} else {
backgroundDrawable = getResources().getDrawable(R.drawable.tab_setup);
}
return backgroundDrawable;
}
}
4、tab切换时图标改变
由于四个tab切换时实现图标改变的.xml文件相似,只列出其中一个。
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:andro></item>
</selector>