package com.robert.sample20;
import android.app.ActionBar;
import android.app.ActionBar.Tab;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.os.Bundle;
public class MainActivity extends Activity {
@Override
protected void
onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ActionBar actionBar=getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
ActionBar.Tab tab=actionBar
.newTab()
.setText("First Tab")
.setTabListener(new AllTabListener<FragmentA>(this,"fragmentA",FragmentA.class));
actionBar.addTab(tab);
tab=actionBar.newTab()
.setText("Second Tab")
.setTabListener(new AllTabListener<FragmentB>(this,"fragmentB",FragmentB.class));
actionBar.addTab(tab);
tab=actionBar.newTab()
.setText("Third Tab")
.setTabListener(new AllTabListener<FragmentC>(this,"fragmentC",FragmentC.class));
actionBar.addTab(tab);
}
public static
class AllTabListener<T extends Fragment> implements ActionBar.TabListener{
private final
Class<T> mClass;
private final
Activity mActivity;
private final
String mTag;
private T mFragment;
public AllTabListener(Activity activity,String
tag,Class<T> clz){
mActivity=activity;
mClass=clz;
mTag=tag;
}
@Override
public void
onTabReselected(Tab tab, FragmentTransaction ft) {
}
@Override
public void
onTabSelected(Tab tab, FragmentTransaction ft) {
if(mFragment==null){
mFragment=(T)T.instantiate(mActivity,mClass.getName());
ft.add(R.id.viewContainer, mFragment,mTag);
}else{
ft.attach(mFragment);
}
}
@Override
public void
onTabUnselected(Tab tab, FragmentTransaction ft) {
if(mFragment!=null){
ft.detach(mFragment);
}
}
}
}
沒有留言:
張貼留言