Android - 显示/隐藏片段留下空白区域

时间:2012-05-21 19:21:23

标签: android webview show-hide fragment

假设:

  1. 屏幕上有两个垂直放置的元素(ViewPager和Fragment)
  2. 第一个当前选定片段(ViewFlipper)中的操作在顶部片段中基于文本和基于WebView的视图之间切换,并隐藏/显示底部片段。
  3. 观察到的:

    1. 隐藏底部片段会留下底部片段所在的空白区域。
    2. 我尝试了Relative和LinearLayout(顶部片段设置为weight=1)但是在删除底部片段后两者都没有效果我底部仍有空白

      这是顶级布局文件:

      <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent"
      android:orientation="vertical" >
      
      <android.support.v4.view.ViewPager
          android:id="@+id/pager"
          android:layout_width="fill_parent"
          android:layout_height="0dip" android:layout_weight="1"/>
      
      <!-- This gets replaced with appropriate fragment at run time -->
      <LinearLayout
          android:id="@+id/scrollFragmentPlaceholder"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:minHeight="110dip" />
      </LinearLayout>
      

      这是切换片段的代码

          Fragment scroll = getSupportFragmentManager().findFragmentById(R.id.scrollFragment);
          if (scroll.isHidden() == isWebView)
              return; // already handled, do nothing
          FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
          if (scroll != null && scroll.isAdded()) {
              if (isWebView) {
                  tr.hide(scroll);
              } else
                  tr.show(scroll);
          }
          tr.commit();
      

      以下是它的外观: Bottom fragment is hidden

1 个答案:

答案 0 :(得分:16)

一个月后,我想出了怎么做。事实证明,简单地隐藏片段是不够的,基本上我需要隐藏/显示包含片段的shell。它仍然是最初在XML中定义的LinearLayout。事实上,在原始布局上设置可见性以显示/隐藏片段就足够了。所以问题中的代码现在看起来像这样:

public void onJobViewToggled(final boolean isWebView) {
    if (isFinishing())
        return;
    final Fragment scroll = getSupportFragmentManager().findFragmentById(R.id.scrollFragment);
    if (scroll.isHidden() == isWebView)
        return; // already handled, do nothing
    final FragmentTransaction tr = getSupportFragmentManager().beginTransaction();
    if (scroll != null && scroll.isAdded()) {
        if (isWebView) {
            tr.hide(scroll);
            // shell is the original placeholder
            shell.setVisibility(View.GONE);
        } else {
            tr.show(scroll);
            shell.setVisibility(View.VISIBLE);
        }
    }
    tr.commit();
}

请注意,您仍然希望显示/隐藏片段以使其正常工作