Passing data back to previous fragment from current fragment

前端 未结 3 1639
攒了一身酷
攒了一身酷 2020-12-16 12:44

I am Using Navigation Drawer in my app. I have one MainActivity and rest of are Fragments. So the issue is Suppose i have three fragments like A,B,C.

Now in A i have

3条回答
  •  清酒与你
    2020-12-16 13:00

    You may call setTargetFragment() when you start the Fragment C from B. Example:

    FragmentC fragmentC = FragmentC.newInstance();
    fragmentC.setTargetFragment(FragmentB.this, REQUEST_CODE);
    getFragmentManager().beginTransaction().replace(R.id.container, fragmentC).commit();
    

    and then when you want to pass data back to fragment B from C, you can call the following code:

    getTargetFragment().onActivityResult(
                    getTargetRequestCode(),
                    Activity.RESULT_OK,
                    new Intent().putExtra("datafrom C", "datafrom C")
    );
    

    and get it from the onActivityResult() method in your fragment B:

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode==REQUEST_CODE && resultCode==Activity.RESULT_OK) {
            String datafromC = data.getStringExtra("datafrom C");   
        }
    }
    

提交回复
热议问题