在onCreate()方法中,设置ActionBar的导航模式:Tab导航
使用其实例方法setNavigationMode():
actionbar.
setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
再依次添加指定个数的Tab页,同时为其添加事件监听器
actionbar.addTab(actionBar.newTab().setText("A").setTabListener(li));
(其中li为自定义的Listener对象,是ActionBar.TabListener的实现类)
举例:
public class MainActivity extends
Activity implements TabListener {
ActionBar actionBar;
List<Fragment> fragments;
FragmentManager fmanager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fragments=new ArrayList<Fragment>();
fmanager=getFragmentManager();
fragments.add(new FragmentR());
fragments.add(new FragmentG());
fragments.add(new FragmentB());
actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
Tab TabR=actionBar.newTab();
TabR.setText("R");
TabR.setTabListener(this);
actionBar.addTab(TabR);
Tab TabG=actionBar.newTab();
TabG.setText("G");
TabG.setTabListener(this);
actionBar.addTab(TabG);
Tab TabB=actionBar.newTab();
TabB.setText("B");
TabB.setTabListener(this);
actionBar.addTab(TabB);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) { }
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int position=tab.getPosition();
FragmentTransaction transaction=fmanager.beginTransaction();
transaction.replace(R.id.ll, fragments.get(position));
transaction.commit();
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
}
|
R.id.ll
的配置如下:
<LinearLayout
android:id="@+id/ll"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
</LinearLayout>
|
效果: