On Android, if you replace a fragment
using FragmentTransaction.replace, the old fragment could still be seen. This is most often caused by not setting the background color of the fragment.
Below is a screenshot of the main fragment.

When the fragment is replaced, both fragments become visible.

To solve the problem, set the android:background
property to “?android:windowBackground
” in the fragment layout files.
1 2 3 4 5 6 7 8 9 10 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?android:windowBackground" tools:context=".MainFragment"> ... </LinearLayout> |
1 2 3 4 5 6 7 8 9 10 |
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="match_parent" android:layout_height="match_parent" android:background="?android:windowBackground" tools:context=".SomeFragment"> ... </LinearLayout> |
The “?android:windowBackground
” property value is based on the current theme, so no hard coding of the background color is involved. After making the changes, the replaced fragment will appear as shown below.
