无法移除另一个中的子片段

时间:2016-11-23 06:35:30

标签: java android android-fragments android-fragmentactivity

我在另一个片段中有一个片段,我添加并提交它,但是当我想删除它时,它不起作用并且总是在它的位置。

主要活动片段

public class MainActivityFragment extends Fragment {
    ScreenUtility screenUtility;

    public MainActivityFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View v = inflater.inflate(R.layout.fragment_main, container, false);

        screenUtility = new ScreenUtility(getActivity());

        TotalAmountFragment totalAmountFragment;
        totalAmountFragment = new TotalAmountFragment();

        if (screenUtility.getOrientation() == 1){
            getChildFragmentManager()
                    .beginTransaction()
                    .add(R.id.main_total_amount_fragment_container, totalAmountFragment, "totalPrice")
                    .commit();
        } else if (screenUtility.getOrientation() == 2 && getChildFragmentManager().findFragmentByTag("totalPrice") != null){
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.remove(totalAmountFragment);
            transaction.commit();
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_CLOSE);
        }
        return v;
    }
}

XML文件

 ...
<FrameLayout
            android:id="@+id/main_total_amount_fragment_container"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:foregroundGravity="center"
            android:layout_centerHorizontal="true"/>

我该怎么办?我做了我想的任何事情。

2 个答案:

答案 0 :(得分:0)

试试此代码

FragmentManager fm = getActivity().getSupportFragmentManager();
if (fm.getBackStackEntryCount() != 0) {
        fm.popBackStack();
    }

答案 1 :(得分:0)

    if (screenUtility.getOrientation() == 1){
        getFragmentManager()
                .beginTransaction()
                .add(R.id.main_total_amount_fragment_container, totalAmountFragment, "totalPrice")
                .commit();
    } else {
        Fragment priceFragment = getActivity().getSupportFragmentManager().findFragmentByTag("totalPrice");
        if (priceFragment != null){
            getActivity().getSupportFragmentManager().beginTransaction().remove(priceFragment).commit();
        }
    }