以编程方式在片段之间切换 [英] Programmatically switching between Fragments
问题描述
我想在1个活动中的2个片段之间切换,因此另一个片段应始终替换当前片段.我虽然找不到我的错误:(
I want to switch between 2 Fragments located in 1 activity, so the other fragment should always replace the current one. I can´t find my error though :(
我的主要活动:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_layout);
Fragment fragment = new FirstFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment, "first");
transaction.addToBackStack(null);
transaction.commit();
}
我的activity_layout:
My activity_layout:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:ignore="MergeRootFrame" />
现在,在FirstFragment的逻辑内(可以正常工作)的某个点,正在调用以下方法
Now, at some point within the logic of the FirstFragment (which works fine), the following method is being called
private void startSecondFragment(){
Fragment fragment = new SecondFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment, "second");
transaction.addToBackStack(null);
transaction.commit();
}
此函数确实完成,没有错误,但是此后立即引发以下异常:
This function does finish without an error, however right afterwards the following exception is getting thrown:
02-11 13:40:30.533: E/AndroidRuntime(907): java.lang.IllegalArgumentException: No view found for id 0x7f070000 (com.myexample.app:id/container) for fragment SecondFragment{412c9388 #0 id=0x7f070000 second}
现在,似乎它目前无法找到ID容器"(第一个Fragment替换了此容器).我如何真正替换第一个片段?
Now, it seems like its not able to find the id "container" at this point (the first Fragment has replaced this container). How can I really replace the first fragment?
推荐答案
应该是这样的:
private void startSecondFragment(){
Fragment fragment = new SecondFragment();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.container, fragment, "second");
transaction.addToBackStack(null);
transaction.commit();
}
您不想获取孩子的FragmentManager,因为您的片段位于您的Activity中,因此您需要相同的fragmentManager.
You don't want to get child's FragmentManager, because your fragments are in your Activity, so you need the same fragmentManager.
这篇关于以编程方式在片段之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!