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;
}
}
}
答案 0 :(得分:0)
是片段是可重复使用的,您可以多次将片段附加/分离到活动。正如您在分离后在文档中看到的那样,片段被销毁,然后在添加到另一个活动时再次创建。