当我单击布局中的后退图标时,它将转到上一个片段,但不会转到被杀死的片段。解决方案是什么?
我正在使用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;
最佳答案
每当您在片段之间进行事务并且想要导航回到先前的片段(“后退”按钮)时,在事务中,必须在提交之前将此事务添加到backStack:
Android文档:
“但是,在调用commit()之前,您可能需要调用addToBackStack(),以便将事务添加到片段事务的后堆栈中。该后堆栈由活动管理,并允许用户返回到上一个碎片状态,方法是按“后退”按钮。”
https://developer.android.com/guide/components/fragments.html#Transactions
// Create new fragment and transaction
Fragment newFragment = new ExampleFragment();
FragmentTransaction transaction = getFragmentManager().beginTransaction();
// Replace whatever is in the fragment_container view with this fragment,
// and add the transaction to the back stack
transaction.replace(R.id.fragment_container, newFragment);
transaction.addToBackStack(null);
// Commit the transaction
transaction.commit();