protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_myfragment_tab);
// 初始化fragmentTabHost, R.id.realtabcontent为tab内容的id,如果不传的话,需要在setcontent中指定
fragmentTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);
String[] tabTitles = new String[]{"user", "discover", "repo", "more"};
for (String title : tabTitles) {
// 通过fragmentTabHost的newTabSpec创建TabSpec
TabHost.TabSpec tabSpec = fragmentTabHost.newTabSpec(title);
View indicator = LayoutInflater.from(this).inflate(R.layout.tab_title, null);
TextView titleView = (TextView)indicator.findViewById(R.id.tab_title);
Drawable drawable = ContextCompat.getDrawable(this, R.drawable.tab_discovery_nor);
drawable.setBounds(0,0,40,40);
titleView.setCompoundDrawablesWithIntrinsicBounds(null, drawable, null, null);
titleView.setText(title);
// setIndicator传入view或者字符串和图标
tabSpec.setIndicator(titleView);
// 传入viewId,intent,或者TabContentFactory,实现生成tab内容view的函数
//TabContentFactory参数无用 addTab会覆盖该值(查看源码发现)
//tabSpec.setContent(new TabHost.TabContentFactory() {
// @Override
// public View createTabContent(String tag) {
// return new View(MyFragmentTab.this);
// }
//});
Bundle args = new Bundle();
args.putString(TestFragment.CONTENT_KEY, title);
fragmentTabHost.addTab(tabSpec, TestFragment.class, args);
}
fragmentTabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
Toast.makeText(MyFragmentTab.this, tabId, Toast.LENGTH_SHORT).show();
}
});
}