当Activity从Fragment开始时,不会调用onActivityResult()

时间:2012-01-12 17:26:07

标签: android android-fragments

我在Android中从相册导入图片时遇到问题,因为永远不会调用onActivityResult()方法。

这是我写的代码(从片段调用而不是活动):

Intent galleryIntent = new Intent(Intent.ACTION_PICK,  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(galleryIntent, PICK_IMAGE);

顺便说一句,我已经定义了onActivityResult(),但它从未触发过:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    Log.d(TAG, "onActivityResult"); // not printed
}

知道这有什么问题吗?

谢谢!

3 个答案:

答案 0 :(得分:112)

要在片段中调用onActivityResult(),您应该调用片段的startActivityForResult()版本,而不是活动的版本。所以在你的片段代码中,替换

getActivity().startActivityForResult(galleryIntent, PICK_IMAGE);

startActivityForResult(galleryIntent, PICK_IMAGE);

答案 1 :(得分:16)

使用此代码:

Intent galleryIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
getActivity().startActivityForResult(galleryIntent, PICK_IMAGE);

onActivityResult必须位于包含Fragment的Activity中。从那里你可以调用片段的任何方法,而不是片段。

MyFragment myFragment = (MyFragment) getSupportFragmentManager().findFragmentById(R.id.fragment);
myFragment .onCameraResult(requestCode, resultCode, intent);

无论你想做什么

答案 2 :(得分:-2)

试试这个代码段:

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null);
    intent.setType("image/*");
    intent.putExtra("return-data", true);
    startActivityForResult(intent, 1);


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

        case 1:
            if(requestCode == 1 && data != null && data.getData() != null){
                Uri _uri = data.getData();

                if (_uri != null) {
                    Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
                    cursor.moveToFirst();
                    final String imageFilePath = cursor.getString(0);
                    File photos= new File(imageFilePath);
                    imageView.setImageBitmap(bitmap);
                    cursor.close();
                }
            }
            super.onActivityResult(requestCode, resultCode, data);
        }
    }