目前,我正在开发针对不同方向的支持。我的景观布局有一个viewpager和tablayout,而我的肖像布局只有一个片段。当我以任何方向启动应用程序时,布局都能正常工作。但是,当在运行时更改方向时(在这种情况下,从纵向更改为横向),viewpager和tablayout将从屏幕上完全消失,即使分配了权重,也仅在父级的高度和宽度上保留了片段。
这使我相信布局没有正确更改。我也没有将android:configuration应用于我的清单。否则,当我改变方向后,其他活动和片段会正常工作。由于某些原因,仅这是行不通的。我将在下面附加XML代码。
<?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>
发布此问题后,突然出现了一个顿悟,它可能是覆盖我的布局的永久片段(即,由于saveInstanceState,来自横向模式下纵向模式堆栈的片段)。
因此,将超级调用更改为null。
super.onCreate(null);
如果有人有兴趣或对像我这样的片段不熟悉,请从Fool-proof way to handle Fragment on orientation change中得到创意。