onActivityResult()在选择图像时返回活动的第一个片段

时间:2018-03-06 11:29:38

标签: android android-layout android-fragments android-activity

我有导航抽屉的主要活动。在那里我有编辑按钮,打开编辑片段。用户从相机或图库中选择的图像应显示在ImageView中。

我面临的问题是我可以成功选择图像,它也会返回onActivityResult()中的图像。但它退出片段并从Camera或Gallery返回后重定向到Main活动片段。

我需要在ImageView中设置图像并在调用onActivityResult()后保留在同一个片段中。

这是我的代码:

EditProfileFragment.java

public class EditProfileFragment extends Fragment {

    RadioButton radioMale, radioFemale;
    Calendar birthDataCalendar = Calendar.getInstance();
    CustomEditText etBirthDate;
    CustomClearableEditText etName, etNumber, etAddress;
    CircleImageView civProfile, civChoose;
    ImageView ivBack;
    Bundle extra;
    byte[] byteArray;
    Bitmap bitmap;
    private static final int REQUEST_CAMERA = 55;
    private static final int SELECT_FILE = 66;


  @Nullable
  @Override
  public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_edit_profile, container, false);
    return view;
}

  @Override
  public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
    etName = view.findViewById(R.id.edit_profile_et_name);
    etNumber = view.findViewById(R.id.edit_profile_et_contact_no);
    etAddress = view.findViewById(R.id.edit_profile_et_address);
    radioMale = view.findViewById(R.id.edit_profile_radio_male);
    radioFemale = view.findViewById(R.id.edit_profile_radio_female);
    etBirthDate = view.findViewById(R.id.edit_profile_et_birth_date);
    civProfile = view.findViewById(R.id.edit_profile_civ_profile);
    civChoose = view.findViewById(R.id.edit_profile_civ_choose);
    ivBack = view.findViewById(R.id.edit_profile_iv_back);

        civChoose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final CharSequence[] options = {"Camera", "Choose from Gallery", "Cancel"};

            AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), R.style.AlertDialogCustom);
            builder.setTitle("Add Photo from..");
            builder.setItems(options, new DialogInterface.OnClickListener() {

                @Override

                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Camera")) {
                        Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
                        cameraIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
                        startActivityForResult(cameraIntent, REQUEST_CAMERA);
                    } else if (options[item].equals("Choose from Gallery")) {
                        Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(intent, SELECT_FILE);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        }
    });

    final DatePickerDialog.OnDateSetListener date = new DatePickerDialog.OnDateSetListener() {

        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear,
                              int dayOfMonth) {
            // TODO Auto-generated method stub
            birthDataCalendar.set(Calendar.YEAR, year);
            birthDataCalendar.set(Calendar.MONTH, monthOfYear);
            birthDataCalendar.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateLabel();
        }
    };

    if (getActivity().getIntent().getStringExtra("signInProfileImage") == null) {

        extra = getActivity().getIntent().getExtras();
        if (extra != null) {
            byteArray = extra.getByteArray("signUpProfileImage");
            bitmap = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
            civProfile.setImageBitmap(bitmap);
        }

    } else {
        String imagePath = getActivity().getIntent().getStringExtra("signInProfileImage");
        Picasso.with(getActivity()).load(imagePath).into(civProfile);
    }

    etBirthDate.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            new DatePickerDialog(getActivity(), date, birthDataCalendar
                    .get(Calendar.YEAR), birthDataCalendar.get(Calendar.MONTH),
                    birthDataCalendar.get(Calendar.DAY_OF_MONTH)).show();
        }
    });

    ivBack.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (getFragmentManager().getBackStackEntryCount() != 0) {
                getFragmentManager().popBackStack();
            }
        }
    });
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        for (Fragment fragment : getChildFragmentManager().getFragments()) {
            fragment.onActivityResult(requestCode, resultCode, data);
        }
    }

    if (REQUEST_CAMERA == requestCode && resultCode == RESULT_OK) {

        Bitmap bitmap = (Bitmap) data.getExtras().get("data");

        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        if (bitmap != null) {
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        }
        String path = MediaStore.Images.Media.insertImage(getActivity().getContentResolver(), bitmap, "", null);


        File filesDir = getActivity().getFilesDir();
        File imageFile = new File(filesDir, "image" + ".jpg");

        OutputStream os;
        try {
            os = new FileOutputStream(imageFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, os);
            os.flush();
            os.close();
        } catch (Exception e) {
            Log.e(getClass().getSimpleName(), "Error writing bitmap", e);
        }

        Uri.parse(path);

        Picasso.with(getActivity()).load(path).noPlaceholder().centerCrop().fit().into(civProfile);
    }

    if (requestCode == SELECT_FILE) {

        Toast.makeText(getActivity(), "Gallery clicked", Toast.LENGTH_SHORT).show();

        Uri selectedImageURI = data.getData();
        String filePath = getRealPathFromURIPath(selectedImageURI, getActivity());
        File file = new File(filePath);

        //RequestBody mFile = RequestBody.create(MediaType.parse("multipart/form-data"), file);


        try {
            InputStream inputStream = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024 * 8];
            int bytesRead = 0;

            while ((bytesRead = inputStream.read(b)) != -1) {
                bos.write(b, 0, bytesRead);
            }

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

        Picasso.with(getActivity()).load(selectedImageURI).noPlaceholder().centerCrop().fit()
                .into((civProfile));
    }
}

private String getRealPathFromURIPath(Uri contentURI, Activity activity) {
    Cursor cursor = activity.getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) {
        return contentURI.getPath();
    } else {
        cursor.moveToFirst();
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
        return cursor.getString(idx);
    }
}

private void updateLabel() {
    String myFormat = "dd-MMM-yyyy"; //In which you need put here
    SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
    etBirthDate.setText(sdf.format(birthDataCalendar.getTime()));
  }
}

MainActivity.java

中的初始化
ivEditProfile.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            getSupportActionBar().hide();
            EditProfileFragment editProfileFragment = new EditProfileFragment();              
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.main_frame, editProfileFragment);
            transaction.addToBackStack(null);
            transaction.commit();
            drawer.closeDrawer(GravityCompat.START);
        }
}); 

提前致谢。

2 个答案:

答案 0 :(得分:5)

我认为根据你的谈话(以及我过去的经历)。您已在onResume()中添加了一些内容,例如打开您的第一个片段代码,因此您需要从onResume()中移除该代码,并且需要将其保留在' onCreate()'你活动中的方法。

答案 1 :(得分:0)

对于我来说,我意识到这是由于我启用了以下选项:

Developer Options -> APPS -> Don't keep activities

在测试图像选择活动时,我禁用了以上选项。并将其重新启用以进行其他测试。