首页 > 代码库 > ActionBar+Fragment实现顶部标签页

ActionBar+Fragment实现顶部标签页

用ActionBar的TABS模式,和Fragment实现程序顶部的标签页切换。

一. MainActivity


        public class MainActivity extends Activity {
 
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
 
// 取得ActionBar,设置为Tab模式
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
 
// 新建2个Tab
ActionBar.Tab tabA = actionBar.newTab().setText("TabA");
ActionBar.Tab tabB = actionBar.newTab().setText("TabB");
 
// 绑定到Fragment
Fragment fragmentA = new FragmentA();
Fragment fragmentB = new FragmentB();
tabA.setTabListener(new MyTabsListener(fragmentA));
tabB.setTabListener(new MyTabsListener(fragmentB));
actionBar.addTab(tabA);
actionBar.addTab(tabB);
}
 
// 监听器类
protected class MyTabsListener implements ActionBar.TabListener {
private Fragment fragment;
 
public MyTabsListener(Fragment fragment) {
this.fragment = fragment;
}
 
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
 
                        // FragmentTransaction 的 replace() 方法切换显示的Fragment
ft.replace(R.id.fragment_place, fragment, null);
}
 
@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
 
}
 
@Override
public void onTabUnselected(Tab arg0, FragmentTransaction arg1) {
// TODO Auto-generated method stub
 
}
}
 
}
 
二. FragmentA.class 与 FragmentB.class
 
public class FragmentB extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_b, container, false);
}
}
 
三. activity_main.xml
 
  要显示切换Fragment的地方:
    <LinearLayout
        android:id="@+id/fragment_place"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical" >
    </LinearLayout>
 
四. fragment_a.xml 与 fragment_b.xml
 
五. 备注:一个在Fragment中getSystemService()的方法
 
新建一个MyApplication类(或使用其它已有Activity)
 
public class MyApplication extends Application {
 
        private static MyApplication instance;
 
        @Override
        public void onCreate() {
                // TODO Auto-generated method stub
                super.onCreate();
                
                instance = this;
        }
 
        public static MyApplication getInstance() {
                // TODO Auto-generated method stub
                return instance;
        }
}
 
需要使用android的系统服务的时候,使用:
Myapplication.getinstance().getsystemservice()

ActionBar+Fragment实现顶部标签页