android:片段在屏幕方向崩溃

问题描述 投票:1回答:1

我制作了两个XML文件,一个用于纵向模式,另一个用于横向模式

当我启动应用程序时,它正常运行,并在第二次翻转屏幕后崩溃并发出此错误:java.lang.IllegalStateException: Fragment has not been attached yet

虽然横向xml文件包含静态片段,但是肖像却没有任何内容(为了在后续步骤中动态添加片段)。这是我的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<fragment
    android:name="com.example.alihaidar.fragmentlab.fragList"
    android:layout_width="0dp"
    android:layout_weight="1"
    android:layout_height="match_parent"
    android:id="@+id/frag_list"
    />
<fragment
    android:name="com.example.alihaidar.fragmentlab.fragContent"
    android:layout_width="0dp"
    android:layout_weight="2"
    android:layout_height="match_parent"
    android:id="@+id/frag_content"
    />
 </LinearLayout>

这是mainActivity它什么都没包含:

public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}
}
android
1个回答
0
投票

您需要进行验证以使用isAdded()方法检查Fragment是否附加到其父级:

if (!isAdded()){
    return;  //Not attached
}else{
   //Attached!
} 

isAdded()如果片段当前已添加到其活动中,则返回true。


另一个选项,在您的活动中定义属性:

<activity 
            android:configChanges="orientation|keyboardHidden|screenSize">

旋转设备时避免破坏父活动。

© www.soinside.com 2019 - 2024. All rights reserved.