从活动反击到片段

时间:2019-01-08 10:40:57

标签: android android-fragments fragment onbackpressed

我有一个 BaseActivity ,它具有以下流程, FragmentA -> Fragment B-> FinalActivity 。现在,我想通过后退按钮 backpress FinalActivity FragmentA

BaseActivity 中,我像这样呼叫 FragmentA

Fragment selectedFragment = FragmentA .newInstance();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_fragment, selectedFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack("Some String");
transaction.commit();

FragmentA 中,我像这样呼叫 FragmentB

Fragment selectedFragment = FragmentB.newInstance();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_fragment, selectedFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.addToBackStack("Some String");
transaction.commit();

FragmentB FinalActivity ,我这样称呼

startActivityForResult(FinalActivity.newIntent(getActivity()), 1);

现在从 FinalActivity 后退按钮中,我要显示 FragmentA

帮我导航。

2 个答案:

答案 0 :(得分:2)

执行此操作的正确方法(由于您有startActivityForResult())将是为活动设置结果,并在结束活动时将信息传递给FragmentB。在您的onBackPressed()方法中,您可以添加以下内容:

Intent resultIntent = new Intent();
String dataString = "Some info you might want to return to the fragment...";
resultIntent.setData(Uri.parse(dataString));
setResult(RESULT_OK, resultIntent);
finish();

然后,在您的 FragmentB 中,您必须覆盖onActivityResult()方法:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
     if (requestCode == request_Code) {
        if (resultCode == RESULT_OK) {
            //here you can pop the FragmentB
        }
    }
}

上面的代码将结束 FinalActivity ->并将RESULT_OK传递给onActivityResult()方法(将在 FragmentB 中调用),然后弹出FragmentB,导致显示FragmentA。

编辑:请注意,您将需要startActivityForResult()中的requestCode与onActivityResult()中的requestCode相同,否则该片段将不知道哪个活动您正在尝试获得。您可以根据需要添加静态全局值。

EDIT2:,现在我知道,在您的代码中,您将看到类似的内容

transaction.addToBackStack("Some String");

这个“某个字符串”实际上应该是Fragment.getName(),以便后退堆栈可以跟踪其中有哪些片段。

答案 1 :(得分:2)

Fragment selectedFragment = FragmentB.newInstance();
FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.container_fragment, selectedFragment);
transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
transaction.commit();

If you want to go back to the Fragment A then You not need to add the Line Given below
When relpace fragment form Fragment A To Fragment B Just remove this Given Line form Your Code

transaction.addToBackStack("Some String");

and Change the Code of the start activity Like this

startActivity(getActivity(),FinalActivity.class);