简体   繁体   中英

How to reach onActivityResult() from Fragment and handle it?

I have a MainActivity and one attached sliding menu to it.
I am calling Fragments separately when the user clicks a button in the sliding menu.
After that, inside one of these Fragments, I am calling a gallery photo chooser and I need to handle it inside the Fragment.

How can I solve this problem?

Override onActivityResult method in fragment and call it from Activity's onActivityResult method by making object of that fragment like following way,

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

I hope it will help you.

You can use this code

Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        startActivityForResult(intent, SELECT_REQUEST);

and within onActivityResult

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == SELECT_REQUEST && resultCode == Activity.RESULT_OK) {
        try {
            InputStream stream = getActivity().getContentResolver()
                    .openInputStream(data.getData());
            pic = BitmapFactory.decodeStream(stream);
            stream.close();
            imageView.setImageBitmap(pic);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

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