这里主要实现用Tab切换不同的Fragment,点击View显示or隐藏ActionBar,把ActionBar 设为透明,使界面更加友好,详细代码见资源里的ActionBarTabs。
ActionBar Tab主要用于Fragment之间的切换,其必须要设置ActionBar.TabListener,详细代码如下
ActionBarActivity.Java:
代码如下 | 复制代码 |
importandroid.app.ActionBar; importandroid.app.Activity; importandroid.app.FragmentTransaction; importandroid.app.ActionBar.Tab; importandroid.os.Bundle; importandroid.os.CountDownTimer; importandroid.view.MotionEvent; importandroid.view.Window; publicclassActionBarActivityextendsActivity { /** Called when the activity is first created. */ @Override publicvoidonCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //使ActionBar变得透明 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); setContentView(R.layout.main); finalActionBar actionBar = getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // remove the activity title to make space for tabs actionBar.setDisplayShowTitleEnabled(false); AFragment aFragment =newAFragment(); actionBar.addTab(actionBar.newTab().setText("Tab-A") .setTabListener(newListenerA(aFragment))); BFragment bFragment =newBFragment(); actionBar.addTab(actionBar.newTab().setText("Tab-B") .setTabListener(newListenerB(bFragment))); } //点击显示or隐藏ActionBar publicbooleanonTouchEvent(MotionEvent event){ ActionBar bar = getActionBar(); switch(event.getAction()){ caseMotionEvent.ACTION_UP: if(bar.isShowing()) bar.hide(); elsebar.show(); break; default: break; } returntrue; } privateclassListenerAimplementsActionBar.TabListener { privateAFragment mFragment; // Called to create an instance of the listener when adding a new tab publicListenerA(AFragment fragment) { mFragment = fragment; } publicvoidonTabSelected(Tab tab, FragmentTransaction ft) { ft.add(R.id.fragment, mFragment,null); } publicvoidonTabUnselected(Tab tab, FragmentTransaction ft) { ft.remove(mFragment); } publicvoidonTabReselected(Tab tab, FragmentTransaction ft) { // do nothing } } } privateclassListenerBimplementsActionBar.TabListener { privateBFragment mFragment; // Called to create an instance of the listener when adding a new tab publicListenerB(BFragment fragment) { mFragment = fragment; } publicvoidonTabSelected(Tab tab, FragmentTransaction ft) { ft.add(R.id.fragment, mFragment,null); } publicvoidonTabUnselected(Tab tab, FragmentTransaction ft) { ft.remove(mFragment); } publicvoidonTabReselected(Tab tab, FragmentTransaction ft) { // do nothing } } } } |
其中涉及到两个Fragment,在前面Fragment的笔记中讲过,这里就不再赘述。类AFragment实现如下,BFragment实现与这类似:
代码如下 | 复制代码 |
publicclassAFragmentextendsFragment { publicView onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { returninflater.inflate(R.layout.alayout, container,false); } } |