android 片段是否可重用 - 我的意思是如果我可以使用如下代码:
class MyTabActivity extends FragmentActivity implements OnClickListener {
Fragment[] tabs = new Fragment[3];
@Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.settings_activity);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
//first xml-defined fragment, it is inside
//FrameLayout with id R.id.loadTarget -> see openTab()
tabs[0] = getSupportFragmentManager().findFragmentById(
R.id.firstFragment);
}
private void openTab(int i) {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.replace(R.id.loadTarget, getTabFragment(i));
ft.addToBackStack(null);
ft.commit();
}
private Fragment getTabFragment(int i) {
if(tabs[i] == null) {
switch(i) {
//0-tab fragment has been allready
//retrieved in onCreate
case 1:
tabs[1] = new MySecondTabFragment();
break;
case 2:
tabs[2] = new MyThirdTabFragment();
break;
}
}
return tabs[i];
}
@Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.button1:
openTab(0);
break;
case R.id.button2:
openTab(1);
break;
case R.id.button3:
openTab(2);
break;
}
}
}