在横向中,我有一个活动,其中 previewFragment 加载到 R.id.fragment_container_child (在屏幕的左三分之一处)和 selectionFragment 加载到 R.id.fragment_container_parent (屏幕的右三分之二)。选择第二个选项卡会将 selectionFragment 更改为 contactFragment 但 previewFragment 保持不变。这一切都很好。
在方向改变时,布局会通过 xml 稍微改变,其中 R.id.fragment_child 现在占据底部三分之一,而不是左侧三分之一。当我改变方向时,问题就出现了。我的操作栏和片段消失了,尽管布局已确认更改。
我没有android:configChanges="orientation"
在 Manifest 文件中定义。以下是我活动的代码:
public class MainActivity extends Activity implements ActionBar.TabListener {
static SelectionFragment selectionFragment;
static ContactFragment contactFragment;
public static PreviewFragment previewFragment;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (findViewById(R.id.fragment_container_child) != null) {
if (savedInstanceState != null) {
return;
}
previewFragment = new PreviewFragment();
selectionFragment = new SelectionFragment();
FragmentTransaction transaction = getFragmentManager()
.beginTransaction();
transaction.add(R.id.fragment_container_child, previewFragment,
"PREVIEW");
transaction.add(R.id.fragment_container_parent, selectionFragment,
"SELECTION");
transaction.commit();
}
final ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText(R.string.menu)
.setTabListener(this));
actionBar.addTab(actionBar.newTab()
.setText(R.string.client_information).setTabListener(this));
sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
}
@Override
public void onRestoreInstanceState(Bundle savedInstanceState) {
}
@Override
public void onSaveInstanceState(Bundle outState) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction transaction) {
switch (tab.getPosition()) {
case 0:
if (selectionFragment == null) {
selectionFragment = new SelectionFragment();
transaction.add(R.id.fragment_container_parent,
selectionFragment, "SELECTION");
} else {
transaction.attach(selectionFragment);
}
break;
case 1:
if (contactFragment == null) {
contactFragment = new ContactFragment();
transaction.add(R.id.fragment_container_parent,
contactFragment, "CONTACT");
} else {
transaction.attach(contactFragment);
}
break;
}
}
@Override
public void onTabUnselected(Tab tab, FragmentTransaction transaction) {
switch (tab.getPosition()) {
case 0:
if (selectionFragment != null)
transaction.detach(selectionFragment);
break;
case 1:
if (contactFragment != null)
transaction.detach(contactFragment);
break;
}
}
@Override
public void onTabReselected(Tab tab, FragmentTransaction transaction) {
}