这个demo演示了如何为Fragment添加tab导航标签,与Activity的用法基本相同,这里需要注意的就是当在不同的tab之间切换时注意fragment与activity的分离与关联。
TabFragment1
public class TabFragment1 extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
TextView tv=new TextView(getActivity());
tv.setText("第一个选项卡中的内容");
return tv;
}
}
MainActivity
public class MainActivity extends Activity {
@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActionBar bar = getActionBar();
// 显示actionbar的标题
bar.setDisplayOptions(0, ActionBar.DISPLAY_SHOW_TITLE);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.addTab(bar
.newTab()
.setText("tab1")
.setTabListener(
new TabFragmentListener<TabFragment1>(this, "tab1",
TabFragment1.class)));
bar.addTab(bar
.newTab()
.setText("tab2")
.setTabListener(
new TabFragmentListener<TabFragment2>(this, "tab2",
TabFragment2.class)));
if(savedInstanceState!=null){
bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
}
}
@SuppressWarnings("deprecation")
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("tab", getActionBar().getNavigationItemCount());
}
// 设置tab的选择监听器
@SuppressWarnings("deprecation")
public class TabFragmentListener<T extends Fragment> implements TabListener {
private Class<T> clz;
private Fragment frg;
private String mTag;
private Activity mActivity;
public TabFragmentListener(Activity activity, String tag, Class<T> clz) {
this.clz = clz;
this.mTag = tag;
this.mActivity = activity;
// 检查当前的Tab中是否已经有了一个fragment,如果则将其与activity分离
// 因为我们在初始化的时候是不显示Tab的
frg = activity.getFragmentManager().findFragmentByTag(mTag);
if (frg != null && !frg.isDetached()) {
FragmentTransaction ft = activity.getFragmentManager()
.beginTransaction();
ft.detach(frg);
ft.commit();
}
}
// 选中时向tab中添加fragment的视图
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if (frg == null) {
frg = Fragment.instantiate(mActivity, clz.getName());
ft.add(android.R.id.content, frg, mTag);
} else {
ft.attach(frg);
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
if (frg != null) {
ft.detach(frg);
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
Toast.makeText(mActivity, "Reselected", 0).show();
}
}
}