方向更改时未加载不同的片段(android)
我创建了一个测试,在同一个活动中显示两个不同的片段。一块是风景画,另一块是肖像画方向更改时未加载不同的片段(android),android,android-fragments,orientation-changes,Android,Android Fragments,Orientation Changes,我创建了一个测试,在同一个活动中显示两个不同的片段。一块是风景画,另一块是肖像画 # My unique activity public class MainActivity extends FragmentActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(
# My unique activity
public class MainActivity extends FragmentActivity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
}
# First Fragment
public class LandscapeFragment extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView v = (TextView) inflater.inflate(R.layout.fragment, container, false);
v.setText("LANDSCAPE");
return v;
}
}
# Other Fragment
public class PortraitFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView v = (TextView) inflater.inflate(R.layout.fragment, container, false);
v.setText("PORTRAIT");
return v;
}
}
我有两个main.xml,一个在layout/中,另一个在layout land/中。每个main.xml都指向要使用的正确片段
<!-- layout-land/main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
android:name="br.luckcheese.test.LandscapeFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" />
<!-- layout/main.xml -->
<?xml version="1.0" encoding="utf-8"?>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/fragment"
android:name="br.luckcheese.test.PortraitFragment"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="5dp" />
<!-- layout/fragment.xml -->
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="30sp" />
当我在横向上打开应用程序时,将显示LandscapeFragment,当我在纵向中打开应用程序时,将显示肖像片段。到目前为止,一切顺利
但是,如果我在“横向”中打开并将设备旋转到“纵向”,则会重新加载并显示“横向”片段。
这不是预期的行为。这个片段应该已经加载了
反过来也会发生同样的事情,如果设备从纵向开始,然后我将其旋转到横向:纵向片段只是重新加载,而不是加载LandscapeFragment
我做错了什么?确保您的manifest.xml中没有:
android:config=“orientation”
。问题在于您的两个布局中,片段ID是相同的。
只需更改这些片段ID,如:
layout/main.xml的碎片肖像
layout land/main.xml的fragmentlanscape。
(还有:
Fragment frag=getSupportFragmentManager().findFragmentById(R.id.Fragment)
框架设置持续时间(假);
)否,我添加到默认清单中的唯一一行是“android:screenOrientation=“sensor””用于activity是否尝试在活动的onCreate()中设置断点,以查看在旋转设备时是否调用此方法?是。它被称为。我在onCreate上为我的活动和每个片段添加了日志消息。当我旋转设备时,错误片段的onCreate在活动的onCreate之后被调用。好的,那个worker。但我不明白为什么需要添加不同的ID?因为在我的代码中,为了设置frag.setRetainInstance(false),我必须测试这两个参数。但是,在通过getResource().getConfiguration().orientation测试当前方向之后,我还完成了使用FrameLayout创建一个独特的布局并通过代码添加片段的工作!