0

我有一个无线电组,它在更改选定的radiobutton时会改变活动中的片段。我有这个代码:

@Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        switch (checkedId) {
            case R.id.main_menu1:
                showOffersFragment();
                break;
            case R.id.main_menu2:
                openMap();
                break;
            case R.id.main_menu3:
                showProductsFragment();
                break;
        }
    }

    private void showProductsFragment() {
        fm = getFragmentManager();
        ft = fm.beginTransaction();
        if (productsFragment == null) {
            bundle = new Bundle();
            bundle.putSerializable(ActivityConstants.PRODUCT_ITEMS, products);
            productsFragment = new ProductFragment();
            productsFragment.setArguments(bundle); ft.add(R.id.main_frag_container, productsFragment, "products");

        } else {
            //TODO
            ft.replace(R.id.main_frag_container, productsFragment, "products");
            productsFragment.loadList(products);
        }

        ft.commit();
    }
private void showOffersFragment() {
        Log.d(TAG, "OFFERS NULL OR :" + (offersFragment == null)+" ITEMS ="+items.size());

        fm = getFragmentManager();
        ft = fm.beginTransaction();

        if (offersFragment == null) {
            bundle = new Bundle();
            bundle.putSerializable(ActivityConstants.OFFER_ITEMS, items);
            offersFragment = new OffersFragment();
            offersFragment.setArguments(bundle);
            ft.add(R.id.main_frag_container, offersFragment,"offers");
        } else {
            ft.replace(R.id.main_frag_container, offersFragment,"offers");
        }
        ft.commit();
    }
  private void openMap() {
        fm = getFragmentManager();
        ft = fm.beginTransaction();
        if(mapFragment==null){
            mapFragment = new MapFragment();
            ft.add(R.id.main_frag_container, mapFragment, "Map");
        }else{
            ft.replace(R.id.main_frag_container, mapFragment, "Map");
        }
        ft.commit();
        mapFragment.getMapAsync(this);
    }

现在的问题是当我在片段之间切换时。它没有立即改变fagments,所以它的反应不是很好。我应该在它们之间切换几次,这样片段才能出现。

谁能告诉我如何优化/使其正常工作?

4

1 回答 1

1

它不会立即响应,因为一开始,一旦您选择了每个选项,就会运行此行ft.add(R.id.main_frag_container, mapFragment, "Map");,这意味着您正在将新片段添加到同一个容器中,而不是替换旧片段。

使用ft.replace(R.id.main_frag_container, mapFragment, "Map");而不是ft.add(R.id.main_frag_container, mapFragment, "Map");. 虽然我可能错了,但是容器(这里是 R.id.main_fragment_container)必须已经添加了片段,一种选择是仅在容器为空时添加片段,否则替换。

如果您希望导航回以前的片段,您可能需要检查addToBackStack 。

于 2015-02-13T10:25:24.797 回答