replace()与多片段无法正常工作

zer*_*uno 7 java android android-fragments

主要活动

package example.antonio.activitydemo;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.support.v4.app.*;

public class MainActivity extends FragmentActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final FragmentManager fragmentManager = getSupportFragmentManager();

        Button button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FirstFragment fragment = new FirstFragment();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                fragmentTransaction.add(R.id.container, fragment);
                fragmentTransaction.commit();
            }
        });

        Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                SecondFragment fragment = new SecondFragment();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();

                fragmentTransaction.replace(R.id.container, fragment);
                fragmentTransaction.commit();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

FirstFragment

package example.antonio.activitydemo;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;

public class FirstFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInsanceState) {
        return inflater.inflate(R.layout.first_fragment, container, false);
    }
}
Run Code Online (Sandbox Code Playgroud)

SecondFragment

package example.antonio.activitydemo;

import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.View;

public class SecondFragment extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInsanceState) {
        return inflater.inflate(R.layout.second_fragment, container, false);
    }
}
Run Code Online (Sandbox Code Playgroud)

他们的XML文件:

main_activity.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"
    android:id="@+id/container"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start1"
        android:id="@+id/button"/>

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start2"
        android:id="@+id/button2"/>

</LinearLayout>
Run Code Online (Sandbox Code Playgroud)

first_fragment.xml

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#000000">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="First!"
        android:textColor="#ffffff"/>


</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

second_fragment.xml就像前一个一样,只有android:text="Second!"

这是奇怪的事情,当我点击Start1按钮4次然后我得到4次这个词First!,直到这里一切正常.如果我单击Start2按钮,我期望的是删除前面的4个片段,添加一个新的片段,外观为Second!.这是我从文档中理解的:

替换添加到容器的现有片段.这与使用相同的containerViewId添加的所有当前添加的片段调用remove(Fragment),然后使用此处给出的相同参数添加(int,Fragment,String)基本相同.

但这是我得到的:

点击4次<code>run()</code>方法:</p>

<pre><code>case OP_REPLACE: {
                    Fragment f = op.fragment;
                    int containerId = f.mContainerId;
                    if (mManager.mAdded != null) {
                        for (int i = 0; i < mManager.mAdded.size(); i++) {
                            Fragment old = mManager.mAdded.get(i);
                            if (FragmentManagerImpl.DEBUG) {
                                Log.v(TAG,
                                        Run Code Online (Sandbox Code Playgroud)

这是FragmentManager.java的片段:

public void removeFragment(Fragment fragment, int transition, int transitionStyle) {
        if (DEBUG) Log.v(TAG, "remove: " + fragment + " nesting=" + fragment.mBackStackNesting);
        final boolean inactive = !fragment.isInBackStack();
        if (!fragment.mDetached || inactive) {
            if (false) {
                // Would be nice to catch a bad remove here, but we need
                // time to test this to make sure we aren't crashes cases
                // where it is not a problem.
                if (!mAdded.contains(fragment)) {
                    throw new IllegalStateException("Fragment not added: " + fragment);
                }
            }
            **if (mAdded != null) {
                mAdded.remove(fragment);
            }**
            if (fragment.mHasMenu && fragment.mMenuVisible) {
                mNeedMenuInvalidate = true;
            }
            fragment.mAdded = false;
            fragment.mRemoving = true;
            moveToState(fragment, inactive ? Fragment.INITIALIZING : Fragment.CREATED,
                    transition, transitionStyle, false);
        }
    }
Run Code Online (Sandbox Code Playgroud)

正如你所看到的,该removeFragment方法删除了一个frament,mAdded但是在run()方法之后,i索引没有被修改,它从它离开的地方重新开始,这样就会丢失一些元素......

小智 0

使用线性布局作为容器无法实现这种情况。

如果您尝试使用片段作为线性布局中的容器,您可以实现这一点。请参阅此链接以获取进一步说明

Android -fragment.replace() 不会替换内容 - 将其放在顶部

否则,请使用以下代码进行按钮单击操作,

Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FirstFragment fragment = new FirstFragment();
            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            fragmentTransaction.add(R.id.container, fragment).addToBackStack(null);
            fragmentTransaction.commit();
        }
    });

    Button button2 = (Button) findViewById(R.id.button2);
    button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            SecondFragment fragment = new SecondFragment();
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            for(int i=0; i < getSupportFragmentManager().getBackStackEntryCount(); i++)
                getSupportFragmentManager().popBackStack();
            fragmentTransaction.replace(R.id.container, fragment);
            fragmentTransaction.commit();
        }
    });
Run Code Online (Sandbox Code Playgroud)

希望这会帮助你..谢谢