本文实例讲述了Android编程之ActionBar Tabs用法。分享给大家供大家参考,具体如下:
这里主要实现用Tab切换不同的Fragment,点击View显示or隐藏ActionBar,把ActionBar 设为透明,使界面更加友好,详细代码见资源里的ActionBarTabs。
ActionBar Tab主要用于Fragment之间的切换,其必须要设置ActionBar.TabListener,详细代码如下
ActionBarActivity.Java:
import android.app.ActionBar; import android.app.Activity; import android.app.FragmentTransaction; import android.app.ActionBar.Tab; import android.os.Bundle; import android.os.CountDownTimer; import android.view.MotionEvent; import android.view.Window; public class ActionBarActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //使ActionBar变得透明 requestWindowFeature(Window.FEATURE_ACTION_BAR_OVERLAY); setContentView(R.layout.main); final ActionBar actiOnBar= getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); // remove the activity title to make space for tabs actionBar.setDisplayShowTitleEnabled(false); AFragment aFragment = new AFragment(); actionBar.addTab(actionBar.newTab().setText("Tab-A") .setTabListener(new ListenerA(aFragment))); BFragment bFragment = new BFragment(); actionBar.addTab(actionBar.newTab().setText("Tab-B") .setTabListener(new ListenerB(bFragment))); } //点击显示or隐藏ActionBar public boolean onTouchEvent(MotionEvent event){ ActionBar bar = getActionBar(); switch(event.getAction()){ case MotionEvent.ACTION_UP: if(bar.isShowing()) bar.hide(); else bar.show(); break; default: break; } return true; } private class ListenerA implements ActionBar.TabListener { private AFragment mFragment; // Called to create an instance of the listener when adding a new tab public ListenerA(AFragment fragment) { mFragment = fragment; } public void onTabSelected(Tab tab, FragmentTransaction ft) { ft.add(R.id.fragment, mFragment, null); } public void onTabUnselected(Tab tab, FragmentTransaction ft) { ft.remove(mFragment); } public void onTabReselected(Tab tab, FragmentTransaction ft) { // do nothing } } } private class ListenerB implements ActionBar.TabListener { private BFragment mFragment; // Called to create an instance of the listener when adding a new tab public ListenerB(BFragment fragment) { mFragment = fragment; } public void onTabSelected(Tab tab, FragmentTransaction ft) { ft.add(R.id.fragment, mFragment, null); } public void onTabUnselected(Tab tab, FragmentTransaction ft) { ft.remove(mFragment); } public void onTabReselected(Tab tab, FragmentTransaction ft) { // do nothing } } } }
其中涉及到两个Fragment,在前面Fragment的笔记中讲过,这里就不再赘述。类AFragment实现如下,BFragment实现与这类似:
public class AFragment extends Fragment { public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { return inflater.inflate(R.layout.alayout, container, false); } }
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android调试技巧与常见问题解决方法汇总》、《Android基本组件用法总结》、《Android视图View技巧总结》、《Android布局layout技巧总结》及《Android控件用法总结》
希望本文所述对大家Android程序设计有所帮助。