Android:从对话框片段调用onActivityResult()

时间:2015-10-09 07:17:30

标签: android

当我在活动中使用对话框片段时,onActivityResult()正在正确调用,但现在我已根据我的要求将活动更改为片段。在这种情况下,图像不会从相机和图库加载到imageview .....

我用来调用对话框片段的代码是......

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

片段中使用的代码........

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{                                                                                // Load the images from gallery and camera
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        String[] filePathColumn = { MediaStore.Images.Media.DATA };

        Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                filePathColumn, null, null, null);
        cursor.moveToFirst();

        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();

        ImageView imageView = (ImageView) getActivity().findViewById(R.id.icon);
        imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));

    }
    else if (requestCode == TAKE_REQUEST && resultCode == Activity.RESULT_OK) {
        pic = (Bitmap) data.getExtras().get("data");
        icon.setImageBitmap(pic);

    }
}

用于片段交易的代码是....

 MyDialogFragment myDialogFragment = new MyDialogFragment();
            myDialogFragment.show(getActivity().getFragmentManager(), "DialogFragment");

对话片段的所有代码.........

 public class MyDialogFragment extends DialogFragment implements View.OnClickListener {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.MY_DIALOG);
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog d = getDialog();

        if (d!=null){
            int width = ViewGroup.LayoutParams.MATCH_PARENT;
            int height = ViewGroup.LayoutParams.MATCH_PARENT;
            d.getWindow().setLayout(width, height);
        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.my_fragment, container, false);

        ImageButton FAB=(ImageButton)root.findViewById(R.id.imagesave);
        FAB.setOnClickListener(this);

        LinearLayout linearbutton=(LinearLayout)root.findViewById(R.id.linearbutton);

        LinearLayout linearLayout=(LinearLayout)root.findViewById(R.id.linear);
        linearLayout.setOnClickListener(this);

        ImageButton text=(ImageButton)root.findViewById(R.id.imageText);
        text.setOnClickListener(this);

        ImageButton pencil=(ImageButton)root.findViewById(R.id.imagePencil);
        pencil.setOnClickListener(this);

        ImageButton gallery=(ImageButton)root.findViewById(R.id.imageGallery);
        gallery.setOnClickListener(this);

        ImageButton camera=(ImageButton)root.findViewById(R.id.imageCamera);
        camera.setOnClickListener(this);

        return root;
    }

    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imagesave: {
                getDialog().dismiss();
                pDialog = new ProgressDialog(getActivity());
                pDialog.setTitle("Saving");
                pDialog.setMessage("please wait..............");
                pDialog.setCancelable(false);
                pDialog.show();

                FAB.setVisibility(View.INVISIBLE);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        pDialog.dismiss();
                        FAB.setVisibility(View.VISIBLE);
                       //Toast.makeText(getActivity(), "File saved successfully", Toast.LENGTH_SHORT).show();
                    }
                }, 2000);


                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.INVISIBLE);
                clear.setVisibility(View.INVISIBLE);

                RelativeLayout content = (RelativeLayout) getActivity().findViewById(R.id.relative);
                content.setDrawingCacheEnabled(true);
                Bitmap bitmap = content.getDrawingCache();

                File myDir = new File("/sdcard/MyCollection");
                myDir.mkdirs();
                Random generator = new Random();
                int n = 10000;
                n = generator.nextInt(n);
                String fname = "Image-" + n + ".jpg";
                File file = new File(myDir, fname);
                if (file.exists()) file.delete();
                FileOutputStream outStream;
                try {
                    outStream = new FileOutputStream(file);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
                    outStream.flush();
                    outStream.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                i = 0;
                break;
            }
            case R.id.linear: {
                getDialog().dismiss();
                break;
            }
            case R.id.imageText:
            {
                editText.setVisibility(View.VISIBLE);
                relativeLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.VISIBLE);
                clear.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.VISIBLE);
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
                Toast.makeText(getActivity(), "You have selected text ", Toast.LENGTH_SHORT).show();
                getDialog().dismiss();
                break;
            }

            case R.id.imagePencil: {
                getDialog().dismiss();

                clear.setVisibility(View.VISIBLE);
                relativeLayout.setVisibility(View.VISIBLE);
                imagesize.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                Toast.makeText(getActivity(),"You have selected pencil ",Toast.LENGTH_SHORT).show();
                i=0;
                break;
            }

            case R.id.imageGallery: {
                getDialog().dismiss();
                clear.setVisibility(View.INVISIBLE);
                relativeLayout.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.VISIBLE);

                final Fragment callingFragment = getActivity().getFragmentManager().findFragmentById();
                Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                callingFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);



                Toast.makeText(getActivity(), "You have selected gallery", Toast.LENGTH_SHORT).show();

                break;
            }

            case R.id.imageCamera: {
                getDialog().dismiss();
                relativeLayout.setVisibility(View.INVISIBLE);
                clear.setVisibility(View.INVISIBLE);
                radioGroup.setVisibility(View.INVISIBLE);
                linearLayout.setVisibility(View.INVISIBLE);
                imagesize.setVisibility(View.VISIBLE);
                startActivityForResult(new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE), TAKE_REQUEST);
                Toast.makeText(getActivity(), "You have selected camera", Toast.LENGTH_SHORT).show();
                break;
            }
        }
    }

}

4 个答案:

答案 0 :(得分:5)

您需要从片段中调用活动。将您的电话改为:

Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
yourFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);

更新:

在你的对话框片段中写下这样的东西:

final Fragment callingFragment = getActivity().getFragmentManager().findFragmentById();
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
callingFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);

根据您的设置,您可能需要getSupportFragmentManager()和/或方法findFragmentByTag()。这取决于您添加片段的方式和位置。

更新2:

final Fragment homeFragment = (HomeFragment)getActivity().getFragmentManager().findFragmentById(R.id.containerView);
Intent in = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
homeFragment.startActivityForResult(in, RESULT_LOAD_IMAGE);

答案 1 :(得分:1)

将在您的片段的父活动中调用

onActivityResult。 你需要把这个事件传递给你的片段。

你可以在这里使用interface作为回调来传递这个事件。

答案 2 :(得分:1)

使用此代码为我工作

case R.id.take_pic:
        startActivityForResult(new Intent(
                android.provider.MediaStore.ACTION_IMAGE_CAPTURE),
                TAKE_REQUEST);
        break;
    case R.id.browse_pic:

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

这里是onActivityresult

    @Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == TAKE_REQUEST && resultCode == Activity.RESULT_OK) {
        pic = (Bitmap) data.getExtras().get("data");
        imageView.setImageBitmap(pic);

    }
    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();
        }
    }
}

答案 3 :(得分:0)

如果父活动也覆盖onActivityResult,则对startActivityForResult的所有调用将返回到父活动。现在,通过调用基类的实现将该调用传递给活动中的所有片段。

换句话说,如果您的活动(及其片段)需要onActivityResult,您所需要做的就是将基本活动称为onActivityResult

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

    //this makes sure the child fragments receive this event
    super.onActivityResult(requestCode, resultCode, data);
    ...

}