Динамический ImageView в RelativeLayout - PullRequest
0 голосов
/ 11 ноября 2019

Я хочу, чтобы пользователи имели возможность загружать изображения через свою галерею или камеру. Я хочу, чтобы эти изображения отображались динамически в RelativeLayout для активности. В моем методе OnCreate у меня есть следующее, которое объявляет Layout и настраивает кнопки для пользователя.

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ImageView imageview = new ImageView(MainActivity.this);
        RelativeLayout relativelayout = findViewById(R.id.relativeLayout);
        LinearLayout.LayoutParams params = new LinearLayout
                .LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);

        // Add image path from drawable folder.
        imageview.setImageResource(***IMAGEVIEW RETURNED FROM onActivityResult***);
        imageview.setLayoutParams(params);
        relativelayout.addView(imageview);

        IDProf = findViewById(R.id.IdProf);
        Upload_Btn = findViewById(R.id.UploadBtn);
        IDProf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                selectImage(MainActivity.this);

            }
        });

        Upload_Btn.setOnClickListener(this);
    }

Пользователь нажимает IDProf и получает следующий метод, где они выбирают либо свою галерею, либо камеру дляИзображение:

private void selectImage(final Context context) {
        final CharSequence[] options = {"Take Photo", "Choose from Gallery", "Cancel"};
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("Add Photo!");
        builder.setItems(options, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                if (options[item].equals("Take Photo")) {

                    isCameraPermissionGranted();
                    captureFromCamera();

                    Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                    File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
                    intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
                    startActivityForResult(intent, 1);
                } else if (options[item].equals("Choose from Gallery")) {

                    isStoragePermissionGranted();
                    pickFromGallery();

                    Intent intent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(intent, 2);
                } else if (options[item].equals("Cancel")) {
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }

После выбора их фото вызывается onActivityResult:

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

        // Result code is RESULT_OK only if the user selects an Image
        if (resultCode == Activity.RESULT_OK)
            switch (requestCode) {
                case GALLERY_REQUEST_CODE:
                    //data.getData return the content URI for the selected Image
                    Uri selectedImage = data.getData();

                    String[] filePathColumn = {MediaStore.Images.Media.DATA};
                    // Get the cursor
                    Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
                    // Move to first row
                    cursor.moveToFirst();
                    //Get the column index of MediaStore.Images.Media.DATA
                    int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                    //Gets the String value in the column
                    String imgDecodableString = cursor.getString(columnIndex);

                    cursor.close();
                    // Set the Image in ImageView after decoding the String
                    imageView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString));
                    break;

                case CAMERA_REQUEST_CODE:
                    imageView.setImageURI(Uri.parse(cameraFilePath));
                    break;
            }

    }

Мне нужно, чтобы изображения для imageView.setImageBitmap(BitmapFactory.decodeFile(imgDecodableString)); и imageView.setImageURI(Uri.parse(cameraFilePath)); отображались динамически в RelativeLayout в OnCreate.

...