android中的Fragments问题

时间:2016-08-15 14:02:07

标签: android android-fragments fragmenttransaction

当我点击布局中的后退图标时,它会转到上一个片段,但它不会转到它被杀死的片段。这是什么解决方案?
我使用finish()和backstack,但它对我不起作用

    back.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

                android.support.v4.app.Fragment onlineFragments = new OnlineFragments();
                android.support.v4.app.FragmentManager fragmentManagerprofile = getActivity().getSupportFragmentManager();
                android.support.v4.app.FragmentTransaction fragmentprofileTransaction = fragmentManagerprofile.beginTransaction();
                fragmentprofileTransaction.replace(R.id.background_fragment, onlineFragments);
                fragmentprofileTransaction.commit();
        }
    });

片段A

        case R.id.recharge:
            HomeActvity.toolbar.setVisibility(View.GONE);
            android.support.v4.app.Fragment Recharge = new Prepaid_recharge();
            android.support.v4.app.FragmentManager fragmentManager = getActivity().getSupportFragmentManager();
            android.support.v4.app.FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            fragmentTransaction.replace(R.id.containerView, Recharge);
            fragmentTransaction.commit();
            break;

1 个答案:

答案 0 :(得分:0)

我使用此代码添加和删除片段。如果我不需要该片段在后栈中,我将布尔值发送为false。从工具栏按后退按钮时执行此操作它打开正确的活动

public static void changeFragment (MyActivity activity, Fragment fragment, int fragmentContainer, boolean addToBackStack){

        FragmentManager fragmentManager = activity.getSupportFragmentManager();
        FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
        fragmentTransaction.replace(fragmentContainer, fragment);

      /*here we keep track of fragments and avoiding last blank fragment by passing true*/
        if(addToBackStack){
            fragmentTransaction.addToBackStack(null);
        }
        fragmentTransaction.commit();
    }