ActionBarSherlock的使用,在上一篇博客中有详细解释,在这里就不进行赘述了,这里我将使用ActionBarSherlock和Fragment结合实现通过点击的方式达到界面切换的效果。废话不多说了,源码如下:
MainActivity.java代码:
public class MainActivity extends SherlockFragmentActivity {
/*定义ActionBar*/
private ActionBar actionBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/*获取Actionbar*/
actionBar = this.getSupportActionBar();
/*设置ActionBar的模式为Tab*/
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
/*新建2个Tab*/
ActionBar.Tab tabA = actionBar.newTab().setText("A Tab");
ActionBar.Tab tabB = actionBar.newTab().setText("B Tab");
/*创建Fragmnet对象*/
Fragment fragmentA = new AFragmentTab();
Fragment fragmentB = new BFragmentTab();
/*设置这两个Tab对应的监听事件*/
tabA.setTabListener(new MyTabListener(fragmentA));
tabB.setTabListener(new MyTabListener(fragmentB));
/*把tabA和tabB添加到actionBar中*/
actionBar.addTab(tabA);
actionBar.addTab(tabB);
}
/**
* 创建TabListener回调
*/
protected class MyTabListener implements TabListener{
/*定义Fragment对象*/
private Fragment fragment;
/*构造函数*/
public MyTabListener(Fragment fragment) {
super();
this.fragment = fragment;
}
/**
* 这个方法很重要
*/
public void onTabSelected(Tab tab, FragmentTransaction ft) {
/*把当前对应的fragment添加到FragmentTransaction中*/
ft.add(R.id.fragment_container, fragment);
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
ft.remove(fragment);
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
AFragmentTab.java代码:
public class AFragmentTab extends SherlockFragment {
/**
* 返回Fragment视图
*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_a, container, false);
return rootView;
}
}
BFragmentTab.java代码:
public class BFragmentTab extends SherlockFragment {
/**
* 返回Fragment视图
*/
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_b, container, false);
return rootView;
}
}
activity_main.xml代码:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:id="@+id/fragment_container"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:orientation="horizontal" >
</LinearLayout>
</LinearLayout>
另外不要忘记,在清单文件中修改主题样式:
android:theme="@style/Theme.Sherlock.Light"
demo下载:http://download.csdn.net/detail/lzm1340458776/7320369