利用actionbar同样也可以轻松的实现tab导航的效果,配合使用fragment实现切换不同view的功能。
若想使用这个功能,1)设置actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS),使actionbar使用tab导航功能。2)调用actionbar的addTab()方法,添加多个tab标签,并为每个tab标签添加时间监听器。
MyFragment.java
01
packagecom.app.main;
02
03
importandroid.annotation.SuppressLint;
04
importandroid.app.Fragment;
05
importandroid.content.Context;
06
importandroid.os.Bundle;
07
importandroid.view.LayoutInflater;
08
importandroid.view.View;
09
importandroid.view.ViewGroup;
10
importandroid.view.ViewGroup.LayoutParams;
11
importandroid.widget.TextView;
12
13
@SuppressLint("NewApi")
14
publicclassMyFragmentextendsFragment {
15
16
@Override
17
publicView onCreateView(LayoutInflater inflater, ViewGroup container,
18
Bundle savedInstanceState) {
19
20
Context context =this.getActivity();
21
22
TextView tv =newTextView(context);
23
24
Bundle arc =this.getArguments();
25
26
inttabs=arc.getInt("key");
27
28
tv.setLayoutParams(newLayoutParams(LayoutParams.FILL_PARENT,
29
LayoutParams.WRAP_CONTENT));
30
31
tv.setText("hello actionbar "+tabs);
32
33
returntv;
34
35
}
36
37
}
main.xml
01
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
02
xmlns:tools="http://schemas.android.com/tools"
03
android:layout_width="match_parent"
04
android:layout_height="match_parent"
05
tools:context=".Main">
06
07
<LinearLayout
08
android:id="@+id/container"
09
android:layout_width="match_parent"
10
android:layout_height="match_parent"
11
android:orientation="vertical"/>
12
13
</RelativeLayout>
Main.java
01
packagecom.app.main;
02
03
importandroid.app.ActionBar;
04
importandroid.app.ActionBar.Tab;
05
importandroid.app.Activity;
06
importandroid.app.FragmentTransaction;
07
importandroid.os.Bundle;
08
09
publicclassMainextendsActivityimplementsActionBar.TabListener {
10
11
ActionBar actionBar =null;
12
13
@Override
14
protectedvoidonCreate(Bundle savedInstanceState) {
15
super.onCreate(savedInstanceState);
16
setContentView(R.layout.main);
17
18
actionBar =this.getActionBar();
19
20
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
21
22
actionBar.addTab(actionBar.newTab().setText("tab1")
23
.setTabListener(this));
24
25
actionBar.addTab(actionBar.newTab().setText("tab2")
26
.setTabListener(this));
27
28
actionBar.addTab(actionBar.newTab().setText("tab3")
29
.setTabListener(this));
30
31
}
32
33
@Override
34
publicvoidonTabReselected(Tab tab, FragmentTransaction ft) {
35
36
}
37
38
@Override
39
publicvoidonTabSelected(Tab tab, FragmentTransaction ft) {
40
41
MyFragment frag =newMyFragment();
42
43
intindex = tab.getPosition() +1;
44
45
Bundle bundle =newBundle();
46
47
bundle.putInt("key", index);
48
49
frag.setArguments(bundle);
50
51
FragmentTransaction action = Main.this.getFragmentManager()
52
.beginTransaction();
53
54
action.replace(R.id.container, frag);
55
56
action.commit();
57
58
}
59
60
@Override
61
publicvoidonTabUnselected(Tab tab, FragmentTransaction ft) {
62
63
}
64
65
}
实现效果: