Spinner项目选择并更改片段

时间:2016-02-15 10:43:37

标签: android android-fragments

当我选择spinner fragment时可以更改,但之前的fragment会保留在activity。如何使previous fragment消失? 我的代码:

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) {
        }
    });
}

问题出在哪里?感谢。

2 个答案:

答案 0 :(得分:1)

替换

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

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

答案 1 :(得分:0)

替换像这样的片段

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