Android - show / hide a fragment will leave an empty area

Given:

  • Two vertically arranged elements on the screen (ViewPager and Fragment)
  • The action in the first fragment that is currently selected (ViewFlipper) switches between the text and WebView representations in the upper fragment and hides / shows the lower fragment.

Observed

  • Hiding the bottom fragment leaves an empty space in which the bottom fragment is located.

I tried both Relative and LinearLayout (with the top fragment set to weight=1 ), but both effects have no effect after removing the fragment from the bottom. I still have an empty space below

Here is the top-level layout file:

 <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> 

Here is the code that switches the fragment

  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(); 

And here is what it looks like: Bottom fragment is hidden

+7
source share
1 answer

A month later, I realized how to do it. It turns out that simply hiding the fragment is not enough, basically I need to hide / show the shell containing the fragment. This is still the LinearLayout that was originally defined in XML. In fact, it’s enough to set the visibility on this source layout to show / hide the fragment. So the question code now looks like this:

 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(); } 

Please note that you still want to show / hide the fragment for this to work

+16
source

All Articles