我刚刚使用制表符+ actionbarsherlock +片段设置了一个项目,并希望在继续之前确保我的方法是正确的 - 主要是使用我的onTabSelected
调用newInstance
,这个例子源自CommonsWare的https://github.com/commonsguy/cw-omnibus/tree/master/ActionBar/TabFragmentDemo示例代码。
我的TabFragmentActivity:
public class TabFragmentActivity extends SherlockFragmentActivity
implements TabListener {
private static final String KEY_POSITION="position";
@Override
public void onCreate(Bundle state) {
super.onCreate(state);
ActionBar bar=getSupportActionBar();
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowTitleEnabled(false);
bar.setDisplayShowHomeEnabled(false);
bar.addTab(bar.newTab().setText(R.string.tab1)
.setTabListener(this).setTag(0));
bar.addTab(bar.newTab().setText(R.string.tab2)
.setTabListener(this).setTag(1));
bar.addTab(bar.newTab().setText(R.string.tab3)
.setTabListener(this).setTag(2));
bar.addTab(bar.newTab().setText(R.string.tab4)
.setTabListener(this).setTag(3));
if (state != null) {
bar.setSelectedNavigationItem(state.getInt(KEY_POSITION));
}
}
@Override
public void onSaveInstanceState(Bundle state) {
state.putInt(KEY_POSITION,
getSupportActionBar().getSelectedNavigationIndex());
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
int i=((Integer)tab.getTag()).intValue();
if (i == 0){
ft.replace(android.R.id.content,
Tab1Fragment.newInstance(i));
}
else if (i == 1){
ft.replace(android.R.id.content,
Tab2Fragment.newInstance(i));
}
else if (i == 2){
ft.replace(android.R.id.content,
Tab3Fragment.newInstance(i));
}
else if (i == 3){
ft.replace(android.R.id.content,
Tab4Fragment.newInstance(i));
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
我的Tab1Fragment:
public class Tab1Fragment extends SherlockFragment {
private static final String KEY_POSITION="position";
static Tab1Fragment newInstance(int position) {
Tab1Fragment frag=new Tab1Fragment();
Bundle args=new Bundle();
args.putInt(KEY_POSITION, position);
frag.setArguments(args);
return(frag);
}
@Override
public View onCreateView(LayoutInflater inflater,
ViewGroup container,
Bundle savedInstanceState) {
View result=inflater.inflate(R.layout.tab1, container, false);
return(result);
}
}
我的Tab1Fragment最终会做很多AsyncTask重载 - 这还行吗?