Android:隐藏/显示或添加/删除片段

时间:2013-04-24 19:52:59

标签: android

case R.id.section:
int orientation = getResources().getConfiguration().orientation;
FrameLayout FragmentContainer = (FrameLayout) findViewById(R.id.FragmentContainer);

switch (orientation) {
case Configuration.ORIENTATION_LANDSCAPE:
    if (FragmentContainer.getVisibility() == View.VISIBLE) {
        getSupportFragmentManager().beginTransaction().remove(new FragmentOne()).commit();
    } else {
        getSupportFragmentManager().beginTransaction().add(R.id.FragmentContainer, new FragmentOne()).commit();
    }
    break;

case Configuration.ORIENTATION_PORTRAIT:
    if (FragmentContainer.getVisibility() == View.VISIBLE) {
        getSupportFragmentManager().beginTransaction().remove(new FragmentTwo()).commit();
    } else {
        getSupportFragmentManager().beginTransaction().add(R.id.FragmentContainer, new FragmentTwo()).commit();
    }
    break;
}

我试图根据我的framelayout的可见性删除/添加片段,但是当我点击菜单项时,没有任何反应......

下面是我在XML中定义的Frame布局。

<FrameLayout
        android:id="@+id/FragmentContainer"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="gone"
     />

我已经尝试了片段的两种add and replace方法。

1 个答案:

答案 0 :(得分:2)

您的framelayoutandroid:visibility="gone"。在代码上我没有看到FragmentContainer.setVisibility(View.VISIBLE);

只需更改两个if / else条件......

if (FragmentContainer.getVisibility() == View.VISIBLE) {
    getSupportFragmentManager().beginTransaction().remove(new FragmentOne()).commit();
    FragmentContainer.setVisibility(View.GONE);
   } else {
    getSupportFragmentManager().beginTransaction().add(R.id.FragmentContainer, new FragmentOne()).commit();
    FragmentContainer.setVisibility(View.VISIBLE);
}