Single intent to let user take picture OR pick image from gallery in Android

前端 未结 4 422
广开言路
广开言路 2020-12-07 08:05

I\'m developing an app for Android 2.1 upwards. I want to enable my users to select a profile picture within my app (I\'m not using the contacts framework).

The id

4条回答
  •  旧巷少年郎
    2020-12-07 08:51

    You can proceed in this way in your Activity:

    private static final int REQUEST_CODE_PICTURE= 1;
    
        /**
         * Click on View to change photo. Sets into View of your layout, android:onClick="clickOnPhoto"
         * @param view View
         */
        public void clickOnPhoto(View view) {
            Intent pickIntent = new Intent();
            pickIntent.setType("image/*");
            pickIntent.setAction(Intent.ACTION_GET_CONTENT);
            Intent takePhotoIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            String pickTitle = "Take or select a photo";
            Intent chooserIntent = Intent.createChooser(pickIntent, pickTitle);
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[] { takePhotoIntent });
            startActivityForResult(chooserIntent, REQUEST_CODE_PICTURE);
        }
    

    Then, add always in your Activity the method onActivityResult:

        @Override
        public void onActivityResult(int requestCode, int resultCode, Intent data) {
            super.onActivityResult(requestCode, resultCode, data);
            if (requestCode == REQUEST_CODE_PICTURE && resultCode == Activity.RESULT_OK) {
                if (data == null) {
                    return;
                }
                try {
                    InputStream inputStream = getContentResolver().openInputStream(data.getData());
                    Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
                    imgPhoto.setImageBitmap(bitmap);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    

提交回复
热议问题