片段之间切换编程 [英] Programatically switching between Fragments

查看:137
本文介绍了片段之间切换编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要到位于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容器(第一个片段已取代此容器)。我怎样才能真正的替换的第一个片段??

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??

感谢您的帮助提前!

Thanks for your help in advance!! Lee

推荐答案

这应该是这样的:

private void startSecondFragment(){

    Fragment fragment = new SecondFragment();
    FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    transaction.add(R.id.container, fragment, "second");
    transaction.addToBackStack(null);
    transaction.commit();

}

您不想让孩子的FragmentManager,因为你的片段在你的活动,所以你需要在同一fragmentManager。

You don't want to get child's FragmentManager, because your fragments are in your Activity, so you need the same fragmentManager.

这篇关于片段之间切换编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆