Fragment shows twice on top of eachother

2019-08-15 05:12发布

问题:

I im displaying fragments in my activity, but seems that some fragments are displaying(instatiating) twice. I'm double checking my code but and in my opinion all should be ok. The issue is when I show the fragment its ok, but after showing another fragment and showing the same fragment it's like reloading the calling the same fragment all over again and it shows updated data - although no data updating was done.

this is how I call my fragments:

public void showFragment(Fragment fragment, Bundle bundle) {
        FragmentManager fm = getFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        fragment.setRetainInstance(true);
        //TODO animation
        if (!fragment.isVisible()) {
            //  ft.setCustomAnimations(R.anim.slide_in, R.anim.slide_out, R.anim.slide_in, R.anim.slide_out);
            fragment.setArguments(bundle);
            ft.replace(R.id.main_frag_container, fragment);
            ft.commit();
        }
        dismissLoading();
    }

And here is one of my fragments:

import android.app.Fragment;
public class ProductFragment extends Fragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
        private final String TAG = ProductFragment.class.getSimpleName();

        private View view;

        private int index = -1;
        private int top = 0;

        private Spinner categorySpinner;
        private ListView listView;
        private ArrayAdapter<CharSequence> cityAdapter, categoryAdapter;
        private ArrayList<Product> items;
        private ProductsAdapter adapter;


        private OnProductSelected productSelectedListener;

        @Override
        public void onAttach(Activity activity) {
            super.onAttach(activity);
            if (activity != null) {
                productSelectedListener = (OnProductSelected) activity;
            }
        }

        @Nullable
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            super.onCreateView(inflater, container, savedInstanceState);
            view = inflater.inflate(R.layout.fragment_products, container, false);
            Log.d(TAG, "PROducts frag started " + getArguments().getSerializable(ActivityConstants.PRODUCT_ITEMS));
            listView = (ListView) view.findViewById(R.id.products_listView);

            if (getArguments().getSerializable(ActivityConstants.PRODUCT_ITEMS) != null) {
                loadList((ArrayList<Product>) getArguments().getSerializable(ActivityConstants.PRODUCT_ITEMS));
            }

            initWidgets(view);
            return view;
        }

        public void loadList(ArrayList<Product> data) {
            items = data;
            adapter = new ProductsAdapter(getActivity(), items);
            Log.d(TAG, "ITEMS SIZE" + items.size());
            listView.setAdapter(adapter);

        }

        @Override
        public void onPause() {
            super.onPause();
            try {
                index = listView.getFirstVisiblePosition();
                View v = listView.getChildAt(0);
                top = (v == null) ? 0 : v.getTop();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }

        @Override
        public void onResume() {
            super.onResume();

    //        setListAdapter(mAdapter);
            if (index != -1) {
                listView.setSelectionFromTop(index, top);
            }


        }

        /**
         * Initialize fragment widgets
         */
        private void initWidgets(View view) {
            categorySpinner = (Spinner) view.findViewById(R.id.products_spinner_cat);
            getActivity().invalidateOptionsMenu();
            ((MainActivity) getActivity()).initActionBar(true);
            listView.setOnItemClickListener(this);

            //set citySpinner adapter
            cityAdapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.cities, android.R.layout.simple_spinner_item);
            cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);

            //set categorySpinner adapter
            categoryAdapter = ArrayAdapter.createFromResource(getActivity(),
                    R.array.categores, android.R.layout.simple_spinner_item);
            categoryAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            categorySpinner.setAdapter(categoryAdapter);
            categorySpinner.setOnItemSelectedListener(this);

            categorySpinner.setSelection(0);
            ((MainActivity) getActivity()).dismissLoading();
            Log.d(TAG, "Fragment inited");
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "onItemClick " + position);
            productSelectedListener.onProductSelected(items.get(position));
        }

        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            Log.d(TAG, "POSITION " + position);

            if (position == 0) {
                position += 1;
            }
            getListing(getResources().getStringArray(R.array.categores)[position].toLowerCase());


        }


        private void getListing(String category) {
            AppHttpClient.getInstance();
            String serverURL = ServerUtil.SERVER_BASE_URL + ServerUtil.PRODUCTS + category;
            Log.d(TAG, "Server url: " + serverURL);
            AppHttpClient.executeMethod(ServerUtil.METHOD_GET_PRODUCTS, serverURL, null, getActivity());
        }


        @Override
        public void onNothingSelected(AdapterView<?> parent) {
            Log.d(TAG, parent.getId() + " ");
        }

    }

Can someone help me solve this? Thanks!

回答1:

First make your view static,then paste the code in onCreateView in fragment.

private static View view=null;

if (view == null) {
            view = inflater.inflate(R.layout.fragment_movies, container, false);

            //code here for first time initialization
        } else if (view != null) {
            //your code here
        }


回答2:

If you use the code you posted to switch from one fragment to another, I would say it may come from how you get the Fragment you pass to your showFragment() method. If you create a new Fragment before passing it to showFragment(), it is normal that a new fragment is created and added on top of the others.

you should use getFragmentManager().findFragmentByTag(String Tag) to get a fragment already in place and re-add it on top of the Fragment stack.