文章目录

布局:
需要FragmentTabHost和一个容纳tab实际类容的view 如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<FrameLayout
android:id="@+id/realtabcontent"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<View
android:layout_width="match_parent"
android:layout_height="1px"
android:background="#dfdfdf" />
<android.support.v4.app.FragmentTabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>

测试代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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();
}
});
}

文章目录