简体   繁体   中英

how to send data from an activity back to a fragment

I am very confused on how to send data between a fragment and an activity, since I found how to send data between activities and even fragments but not from an activity that is called from a fragment (which I think is different because I tried those methods and they didn't work).

In my case I want to start a new activity from a fragment and send some data (time from a timepicker) back to the fragment that started the activity.

So basically my question is,

How do I start a new Activity from a class that extends fragment?

And then, How do send data back to the fragment.

to start activity from fragment which deliver you some result back; you can use startActivityForResult :

For ex:

    public class YourFragment extends Fragment {

    private static final int REQUEST_GET_DATA_FROM_SOME_ACTIVITY = 1;

    //start activity for result
    ....
    Intent intent = new Intent(getActivity(),SomeActivity.class);
    startActivityForResult(intent,REQUEST_GET_DATA_FROM_SOME_ACTIVITY)

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == REQUEST_GET_DATA_FROM_SOME_ACTIVITY && resultCode == Activity.RESULT_OK) {
          Bundle extras = data.getExtras();
           //get data from extras
        }
    }

}

and inside your activity

public class SomeActivity extends Activity {

      //complete process and deliver result
      ........
      Intent resultIntent = new Intent();
      resultIntent .putExtra("extra","put anything");
      setResult(Activity.RESULT_OK, resultIntent);
      finish();
   }
}

Declare a field in fragment (you will see usage below)

private static int RC_SOME_ACTIVITY = 101;

To start activity from fragment

startActivityForResult(new Intent(getContext(), SomeActivity.class), RC_SOME_ACTIVITY);

In the the started activity to send data back

Intent data = new Intent();
// add data to intent

setResult(RESULT_OK, data);
finish();

In your fragment you will need to override onActivityResult to extract data in

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == RC_SOME_ACTIVITY && resultCode == RESULT_OK) {
        // extract data 
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM