Transfer data back to the previous fragment from the current fragment

I use the navigation box in my application. I have one MainActivity, and the rest are fragments. So the problem is that I have three fragments like A, B, C.

Now I have one button, and I send data from A> B.
For example putSring ("datafrom A", "datafrom A"),
Now in B I get data from A.
I have one button in B, and I send data from B> C.
For example putSring ("data from B", "data from B"),
Now in C I get data from B.
Then I have one button in C and send data from C> B.
For example putSring ( "datafrom C", "datafrom C");

So it looks like in B I am getting data from two different fragments. I tried using all the actions and it works well with startActivityforresult. but how can I control when all are fragments.

+15
source share
2 answers

When u sends data from fragment A to fragment B, use the same logical values ​​as below: -

FragmentA → FragmentB

FragmentB ldf = new FragmentB ();
Bundle args = new Bundle();
args.putBoolean("BOOLEAN_VALUE",true);
ldf.setArguments(args);

getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

And when u sends data from fragment C to fragment B, use the same BOOLEAN that is used in fragment AB, as shown below -

FragmentC → FragmentB

FragmentB ldf = new FragmentB ();
    Bundle args = new Bundle();
    args.putBoolean("BOOLEAN_VALUE",false);
    ldf.setArguments(args);

    getFragmentManager().beginTransaction().add(R.id.container, ldf).commit();

And in the latter case, we must check that the value is received in FragmentB, where, for example, a fragment A OR FragemntC

Fragmentb

   Boolean getValue= getArguments().getBoolean("BOOLEAN_VALUE");  
   if(getValue)
   {
    //VALUE RECEIVED FROM FRAGMENT A
   }
   else
   {
   //VALUE RECEIVED FROM FRAGMENT C
   }
+5
source

You can call setTargetFragment () when you run the C fragment from B. Example:

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

, B C, :

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

onActivityResult() 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");   
    }
}
+53

Source: https://habr.com/ru/post/1671959/


All Articles