简体   繁体   中英

Spinner item select and change fragments

When I select the spinner fragment can change but previous fragment stay in activity . How to make disappear the previous fragment ? My code:

public void addListenerOnSpinnerItemSelectionAndItemSelectHandling() {
    spinner = (Spinner) findViewById(R.id.spinner);
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            //Toast.makeText(UsersActivity.this, String.valueOf(spinner.getSelectedItem()),Toast.LENGTH_SHORT).show();
            if(String.valueOf(spinner.getSelectedItem()).equals("Корзина")) {
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                ShoppingBasket sb = (ShoppingBasket)fragmentManager.findFragmentByTag("sb");
                if(sb == null){
                    sb = new ShoppingBasket();
                    fragmentTransaction.add(R.id.fragment_container, sb, "sb");
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                }
                else {
                    fragmentTransaction.remove(sb);
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                }

                fragmentTransaction.commit();
            }

            if(String.valueOf(spinner.getSelectedItem()).equals("Пополнить баланс")) {
                FragmentManager fragmentManager = getFragmentManager();
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                AddBalance ab = null;
                if(ab == null){
                    ab = new AddBalance();
                    fragmentTransaction.add(R.id.fragment_container2, ab, "ab");
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
                }
                else {
                    fragmentTransaction.remove(ab);
                    fragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
                }

                fragmentTransaction.commit();
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });
}

Where is the problem? Thanks.

Replace

fragmentTransaction.add(R.id.fragment_container, sb);

with

fragmentTransaction.replace(R.id.fragment_container, sb);

Replace fragments like this

fm.beginTransaction()
        .replace(fragmentB, R.id.container)
.addToBackstack(null)
.commit();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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