利用actionbar同样也可以轻松的实现tab导航的效果,配合使用fragment实现切换不同view的功能。
若想使用这个功能,1)设置actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS),使actionbar使用tab导航功能。2)调用actionbar的addTab()方法,添加多个tab标签,并为每个tab标签添加时间监听器。
MyFragment.java
package com.app.main;import android.annotation.SuppressLint;import android.app.Fragment;import android.content.Context;import android.os.Bundle;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.view.ViewGroup.LayoutParams;import android.widget.TextView;@SuppressLint("NewApi")public class MyFragment extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { Context context = this.getActivity(); TextView tv = new TextView(context); Bundle arc = this.getArguments(); int tabs=arc.getInt("key"); tv.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)); tv.setText("hello actionbar "+tabs); return tv; }}main.xml
Main.java
package com.app.main;import android.app.ActionBar;import android.app.ActionBar.Tab;import android.app.Activity;import android.app.FragmentTransaction;import android.os.Bundle;public class Main extends Activity implements ActionBar.TabListener { ActionBar actionBar = null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); actionBar = this.getActionBar(); actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS); actionBar.addTab(actionBar.newTab().setText("tab1") .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText("tab2") .setTabListener(this)); actionBar.addTab(actionBar.newTab().setText("tab3") .setTabListener(this)); } @Override public void onTabReselected(Tab tab, FragmentTransaction ft) { } @Override public void onTabSelected(Tab tab, FragmentTransaction ft) { MyFragment frag = new MyFragment(); int index = tab.getPosition() + 1; Bundle bundle = new Bundle(); bundle.putInt("key", index); frag.setArguments(bundle); FragmentTransaction action = Main.this.getFragmentManager() .beginTransaction(); action.replace(R.id.container, frag); action.commit(); } @Override public void onTabUnselected(Tab tab, FragmentTransaction ft) { }}实现效果: