当相机活动返回时,承载这个片段的活动有它的onActivityResult被调用。

我的片段开始一个活动的结果与意图发送给相机拍照。图片应用程序加载正常,拍摄照片并返回。然而onActivityResult从未被击中。我设置了断点,但什么都没有触发。一个片段可以有onActivityResult吗?我想是的,因为它是一个已提供的函数。为什么这个没有被触发?

ImageView myImage = (ImageView)inflatedView.findViewById(R.id.image);
myImage.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View view) {
        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 1888);
    }
});

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if( requestCode == 1888 ) {
        Bitmap photo = (Bitmap) data.getExtras().get("data");
        ((ImageView)inflatedView.findViewById(R.id.image)).setImageBitmap(photo);
    }
}

当前回答

简而言之,

在fragment中,声明fragment fragment = this;

之后使用fragment.startActivityForResult。

结果将在activityResult中返回。

其他回答

public class takeimage extends Fragment {

    private Uri mImageCaptureUri;
    private static final int PICK_FROM_CAMERA = 1;
    private static final int PICK_FROM_FILE = 2;
    private String mPath;
    private ImageView mImageView;
    Bitmap bitmap = null;
    View view;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.activity_send_image, container, false);
        final String[] items = new String[] { "From Camera", "From SD Card" };
        mImageView = (ImageView)view.findViewById(R.id.iv_pic);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.select_dialog_item, items);
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("Select Image");

        builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int item) {
                if (item == 0) {
                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File file = new File(Environment.getExternalStorageDirectory(), "tmp_avatar_"
                        + String.valueOf(System.currentTimeMillis())
                        + ".jpg");
                    mImageCaptureUri = Uri.fromFile(file);

                    try {
                        intent.putExtra(
                            android.provider.MediaStore.EXTRA_OUTPUT,
                            mImageCaptureUri);
                        intent.putExtra("return-data", true);

                        getActivity().startActivityForResult(intent,
                            PICK_FROM_CAMERA);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                    dialog.cancel();
                } else {
                    Intent intent = new Intent();

                    intent.setType("image/*");
                    intent.setAction(Intent.ACTION_GET_CONTENT);

                    getActivity().startActivityForResult(
                        Intent.createChooser(intent,
                            "Complete action using"), PICK_FROM_FILE);
                }
            }
        });
        final AlertDialog dialog = builder.create();

        Button show = (Button) view.findViewById(R.id.btn_choose);
        show.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                // Switch the tab content to display the list view.
                dialog.show();
            }
        });

    return view;
    }

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

        if (resultCode != Activity.RESULT_OK)
            return;

        if (requestCode == PICK_FROM_FILE) {
            mImageCaptureUri = data.getData();
            // mPath = getRealPathFromURI(mImageCaptureUri); //from Gallery

            if (mPath == null)
                mPath = mImageCaptureUri.getPath(); // from File Manager

            if (mPath != null)
                bitmap = BitmapFactory.decodeFile(mPath);
        } else {
            mPath = mImageCaptureUri.getPath();
            bitmap = BitmapFactory.decodeFile(mPath);
        }
        mImageView.setImageBitmap(bitmap);  
    }

    public String getRealPathFromURI(Uri contentUri) {
        String [] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = managedQuery(contentUri, proj, null, null,null);

        if (cursor == null) return null;

        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }
} 

大多数答案都说你必须在你的Fragment的宿主Activity中调用super.onActivityResult(…)。但这似乎对我不起作用。

所以,在你的主机活动中,你应该调用你的片段onActivityResult(…)。这里有一个例子。

public class HostActivity extends Activity {

    private MyFragment myFragment;

    protected void onActivityResult(...) {
        super.onActivityResult(...);
        this.myFragment.onActivityResult(...);
    }
}

在HostActivity的某些时候,你需要分配这个。你正在使用的片段。或者,使用FragmentManager来获取Fragment,而不是在HostActivity中保留对它的引用。另外,在你尝试调用this.myFragment.onActivityResult(…);;

在你的片段中,调用

this.startActivityForResult(intent, REQUEST_CODE);

这里this指的是片段。否则就照@Clevester说的做:

Fragment fragment = this;
....
fragment.startActivityForResult(intent, REQUEST_CODE);

我还得打电话

super.onActivityResult(requestCode, resultCode, data);

在父活动的onActivityResult中使其工作。

(我改编自@Clevester的回答。)

宿主活动覆盖onActivityResult(),但它没有为未处理的结果代码调用super.onActivityResult()。显然,即使片段是执行startActivityForResult()调用的片段,活动也会首先处理结果。当您考虑片段的模块化时,这是有意义的。一旦我为所有未处理的结果实现了super.onActivityResult(),片段就有机会处理结果。

还有来自@siqing的回答:

为了在你的片段中得到结果,确保你调用startActivityForResult(intent,111);代替getActivity().startActivityForResult(intent,111);在你的碎片里。

我在使用ChildFragmentManager时有同样的问题。管理器不会将结果传递给嵌套片段,您必须在基本片段中手动执行此操作。

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    super.onActivityResult(requestCode, resultCode, intent);
    Fragment fragment = (Fragment) getChildFragmentManager().findFragmentByTag(childTag);
    if (fragment != null) {
        fragment.onActivityResult(requestCode, resultCode, intent);
    }
}