简体   繁体   English

片段已经添加,虽然它只添加了一次

[英]Fragment already added although it is only added once

I am trying to make an activity consisted of 4 fragments.我正在尝试制作由 4 个片段组成的活动。 Each fragment gets replaced by another upon swiping (not destroying).每个片段在滑动(不破坏)时被另一个片段替换。

When I reach the 3rd fragment by swiping to left twice, the application terminates with error code saying当我通过向左滑动两次到达第三个片段时,应用程序终止并显示错误代码

java.lang.IllegalStateException: Fragment already added: [4th fragment] {8e8204d #3 id=0x7f080033 android:switcher:2131230771:3} java.lang.IllegalStateException:已添加片段:[第 4 个片段] {8e8204d #3 id=0x7f080033 android:switcher:2131230771:3}

But the problem is that I do not add any fragment after first onCreate called by the activity containing the fragments.但问题是,在包含片段的活动调用的第一次 onCreate 之后,我没有添加任何片段。

Could anyone give me an advice which directly I should take to resolve this issue?谁能给我一个建议,我应该直接采取哪些措施来解决这个问题?

Code for my main activity is as below.我的主要活动的代码如下。

import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;

import android.widget.EditText;

import java.util.ArrayList;
import java.util.List;

public class AnalysisActivity extends AppCompatActivity implements LocationFragment.OnFragmentInteractionListener, TypeFragment.OnFragmentInteractionListener, CountFragment.OnFragmentInteractionListener, SummaryFragment.OnFragmentInteractionListener {

    /**
     * The {@link android.support.v4.view.PagerAdapter} that will provide
     * fragments for each of the sections. We use a
     * {@link FragmentPagerAdapter} derivative, which will keep every
     * loaded fragment in memory. If this becomes too memory intensive, it
     * may be best to switch to a
     * {@link android.support.v4.app.FragmentStatePagerAdapter}.
     */
    private SectionsPagerAdapter mSectionsPagerAdapter;

    /**
     * The {@link ViewPager} that will host the section contents.
     */
    private ViewPager mViewPager;

    private LocationFragment locationFragment;
    private TypeFragment typeFragment;
    private CountFragment countFragment;
    private SummaryFragment summaryFragment;


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

        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
        locationFragment = new LocationFragment();
        typeFragment = new TypeFragment();
        countFragment = new CountFragment();
        summaryFragment = new SummaryFragment();
        mSectionsPagerAdapter.addFragment(locationFragment, "LocationFragment");
        mSectionsPagerAdapter.addFragment(summaryFragment, "SummaryFragment");
        mSectionsPagerAdapter.addFragment(typeFragment, "TypeFragment");
        mSectionsPagerAdapter.addFragment(countFragment, "CountFragment");

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.container);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        getSupportFragmentManager().beginTransaction()
                .replace(R.id.container, locationFragment)
                .replace(R.id.container, summaryFragment)
                .replace(R.id.container, typeFragment)
                .replace(R.id.container, countFragment)
                .commit();



    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_analysis, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        public PlaceholderFragment() {

        }

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = null;

            switch (getArguments().getInt(ARG_SECTION_NUMBER)) {
                case 1:
                    rootView = inflater.inflate(R.layout.fragment_location, container, false);
                    break;
                case 2:
                    rootView = inflater.inflate(R.layout.fragment_type, container, false);
                    break;
                case 3:
                    rootView = inflater.inflate(R.layout.fragment_count, container, false);
                    break;
                case 4:
                    rootView = inflater.inflate(R.layout.fragment_summary, container, false);
                    break;
            }


            return rootView;
        }
    }

    @Override
    public void onInputLocationSent(CharSequence input) {
        summaryFragment.updateEditText_summary_location(input);
    }

    @Override
    public void onInputTypeSent(CharSequence input) {
        summaryFragment.updateEditText_summary_type(input);
    }

    @Override
    public void onInputCountSent(CharSequence input) {
        summaryFragment.updateEditText_summary_count(input);
    }

    @Override
    public void onInputSummaryLocationSent(CharSequence input) {

    }

    @Override
    public void onInputSummaryTypeSent(CharSequence input) {

    }

    @Override
    public void onInputSummaryCountSent(CharSequence input) {

    }


    /**
     * A {@link FragmentPagerAdapter} that returns a fragment corresponding to
     * one of the sections/tabs/pages.
     */
    public class SectionsPagerAdapter extends FragmentPagerAdapter {
        private final List<Fragment> mFragmentList = new ArrayList<>();
        private final List<String> mFragmentTitleList = new ArrayList<>();

        public SectionsPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        public void addFragment(Fragment fragment, String title) {
            mFragmentList.add(fragment);
            mFragmentTitleList.add(title);
        }

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
//            return PlaceholderFragment.newInstance(position + 1);
            return mFragmentList.get(position);
        }

        @Override
        public int getCount() {
            return mFragmentList.size();
        }
    }
}

Remove the following code.删除以下代码。 I am not sure what the intent is but it is probably the source of your problem.我不确定意图是什么,但这可能是您问题的根源。

getSupportFragmentManager().beginTransaction()
        .replace(R.id.container, locationFragment)
        .replace(R.id.container, summaryFragment)
        .replace(R.id.container, typeFragment)
        .replace(R.id.container, countFragment)
        .commit();

The result of the above code is to replace R.id.container with locationFragment then summaryFragment then typeFragment and, finally, countFragment which is what R.id.container will actually contain at the end.上面的代码的结果是,以取代R.id.container与当时locationFragment summaryFragment然后typeFragment,最后,countFragment这是什么R.id.container实际上将包含在最后。 As a result, when you swipe, the third swipe is to countFragment which was added by the above code so is a duplicate.结果,当您滑动时,第三次滑动是对由上述代码添加的countFragment进行复制,因此是重复的。

FragmentPagerAdapter will handle the fragments for you. FragmentPagerAdapter将为您处理片段。 You don't need to add them yourself.您不需要自己添加它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM