Getting Results with Fragments

In this chapter, you did not need a result back from the started activity. But what if you did? Your code would look a lot like it did in GeoQuiz. Instead of using Activity’s startActivityForResult(…) method, you would use Fragment.startActivityForResult(…). Instead of overriding Activity.onActivityResult(…), you would override Fragment.onActivityResult(…):

public class CrimeListFragment extends Fragment {

    private static final int REQUEST_CRIME = 1;
    ...
    private class CrimeHolder extends RecyclerView.ViewHolder
            implements View.OnClickListener {
        ...
        @Override
        public void onClick(View view) {
            Intent intent = CrimeActivity.newIntent(getActivity(), mCrime.getId());
            startActivityForResult(intent, REQUEST_CRIME);
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CRIME) {
            // Handle result
        }
    }
    ...
}

Fragment.startActivityForResult(Intent, int) is similar to the Activity method with the same name. It includes some additional code to route the result to your fragment from its host activity.

Returning results from a fragment is a bit different. A fragment can receive a result from an activity, but it cannot have its own result. Only activities have results. So while Fragment has its own startActivityForResult(…) and onActivityResult(…) methods, it does not have any setResult(…) methods.

Instead, you tell the host activity to return a value. Like this:

public class CrimeFragment extends Fragment {
    ...
    public void returnResult() {
        getActivity().setResult(Activity.RESULT_OK, null);
    }
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.122.195