Search code examples
androidandroid-fragmentsandroid-viewpager

TabLayout and ViewPager disappearing after Orientation Change


Currently, I'm developing support for different orientations. I have a viewpager and tablayout for my landscape layout and only a single fragment for my portrait layout. When I launch the application in whichever orientation, the layouts work fine. However, when the orientation is changed during runtime, in this case from portrait to landscape, the viewpager and tablayout completely disappears from the screen, leaving only the fragment at parent height and width even though a weight is allocated.

This led me to believe that the layout is not changing properly. I do not have android:configurations applied to my manifest as well. Otherwise, other activities and fragments work fine when I have their orientation changed. For some reason, only this does not work. I'll attach the XML code below.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/drawer"
tools:context=".HomeActivity">

<FrameLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"
    tools:ignore="UselessParent">
    <fragment
        android:id="@+id/none"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:tag="fragment_tag"
        android:name="com.example.trackeths.HomeFragment" />
</FrameLayout>


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:layout_weight="1">

    <com.google.android.material.tabs.TabLayout
        android:id="@+id/tabLayout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:tabGravity="fill"
        app:tabMode="fixed"
        app:tabTextColor="#fff"
        app:tabIndicatorColor="#fff"
        android:background="@color/colorPrimaryDark"
        />

    <androidx.viewpager.widget.ViewPager
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:id="@+id/viewPager"/>

</LinearLayout>


Solution

  • After posting this question, suddenly had an epiphany that it could be a persistent fragment that overwrites my layouts (i.e. fragment from portrait mode stacks on landscape mode due to savedInstanceState).

    Hence, changed the super call to null.

    super.onCreate(null);
    

    Got the idea from Fool-proof way to handle Fragment on orientation change if anyone's interested or is new to fragments like I am.