android使用片段从相机或画廊获取照片

时间:2017-11-08 07:08:41

标签: android android-fragments android-photos

我正在使用FragmentPagerAdapter三个标签。每个标签都有多个fragments,其中一个片段我要求从图库或相机中获取照片。问题是onActivityResult()主持Activity托管标签的调用不是Fragment的标签。帮助感谢。

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    switch (requestCode) {
        case MEDIA_TYPE_IMAGE_FROM_GALLERY:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = data.getData();
                String realPath = getImageRealPath(selectedImage);
                realPaths.add(realPath);
                Glide.with(mActivity)
                        .load(realPath)
                        .into(profile_imv);
            }
            break;
        case MEDIA_TYPE_IMAGE_BY_CAMERA:
            if (resultCode == RESULT_OK) {
                Uri selectedImage = data.getData();
                String realPath = getImageRealPath(selectedImage);
                realPaths.add(realPath);
                Glide.with(mActivity)
                        .load(realPath)
                        .into(profile_imv);
            }
            break;
    }
}

以下是我为图库和相机调用Intent的方法

public void choosePhotoFromGallary() {
    Intent galleryIntent = new Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

    startActivityForResult(galleryIntent, MEDIA_TYPE_IMAGE_FROM_GALLERY);
}

private void takePhotoFromCamera() {
    Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
    if (intent.resolveActivity(mActivity.getPackageManager()) != null) {
        startActivityForResult(intent, MEDIA_TYPE_IMAGE_BY_CAMERA);
    }
}

这是MainACtivity onActivityResult()代码

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    Fragment fragment = getSupportFragmentManager().findFragmentByTag("USER_DETAILS");
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, data);
    }
}

2 个答案:

答案 0 :(得分:0)

getActivity().startActivityForResult(..)更改为startActivityForResult(..)这会将结果意图传递给片段的onActivityResult(..)

在这篇SO here

中精美解释

答案 1 :(得分:0)

覆盖片段内的onActiviyResult()并在那里重写代码。