无法替换图像视图,用于来自相机或画廊的图像(它不起作用)

Can't replace image view, for image from a camera or gallery (It doesn't work)

我无法用画廊或相机中的其他图像替换图像,当我显示我的画廊中的图像并选择图像时,这不会替换图像。此外,当我打算用相机拍摄图像时,这并没有显示,我也无法拍照。我想替换片段中的图像,这是片段的代码。对于相机,起初我认为这可能是因为我没有正确添加相机清单,但后来我看到了这个,我认为这是正确的。

public class SettingsFragment extends Fragment {
    private ImageView ivImage;
    private String userChoosenTask;
    private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
    private Button btnSelect;
    public SettingsFragment() {
    }
    private void cameraIntent(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent, REQUEST_CAMERA);
    }
    private void galleryIntent(){
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(Intent.createChooser(intent, "Selecciona una imagen"), SELECT_FILE);
    }
    @SuppressWarnings("deprecation")
    public void onSelectFromGalleryResult(Intent data){
        Bitmap bm = null;
        if(data != null){
            try{
                bm = MediaStore.Images.Media.getBitmap(getActivity().getApplicationContext().getContentResolver(),data.getData());
            }catch(IOException e){
                e.printStackTrace();
            }
        }
        ivImage.setImageBitmap(bm);
    }

    private void onCaptureImageResult(Intent data){
        Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        thumbnail.compress(Bitmap.CompressFormat.JPEG,90, bytes);
        File destination = new File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()+".jpg");
        FileOutputStream fo;
        try{
            destination.createNewFile();
            fo = new FileOutputStream(destination);
            fo.write(bytes.toByteArray());
            fo.close();
        }catch (FileNotFoundException e){
            e.printStackTrace();
        }catch (IOException e){
            e.printStackTrace();
        }
        ivImage.setImageBitmap(thumbnail);
    }private void SelectImage(){
        final CharSequence[] items = {"Realizar foto", "Selecciona una imagen", "Cancelar"};
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setTitle("Añadir foto");
        builder.setItems(items, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int item) {
                boolean result = Utility.checkPermission(getContext());
                if(items[item].equals("Realizar una foto")){
                    userChoosenTask = "Realizar una foto";
                    if(result)
                        cameraIntent();
                }else if(items[item].equals("Selecciona una imagen")){
                    userChoosenTask = "Selecciona una imagen";
                    if(result){
                        galleryIntent();
                    }
                }else if(items[item].equals("Cancelar")){
                    dialog.dismiss();
                }
            }
        });
        builder.show();
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        final View rootView = inflater.inflate(R.layout.fragment_perfil, container, false);
        final Fragment settings = new Sett();
        final Fragment datospersonales = new datospersonales();
        btnSelect = (Button) rootView.findViewById(R.id.btnSelectPhoto);


        final FragmentManager fragmentManager = getFragmentManager();
        final ImageButton optsel = (ImageButton) rootView.findViewById(R.id.optsel);
        final Button alerta = (Button) rootView.findViewById(R.id.alerta);

        btnSelect.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                SelectImage();
            }
        });


        optsel.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
                fragmentTransaction.replace(R.id.fragmentContainer, settings).commit();
            }
        });
        alerta.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                Notification();
            }
        });
        ivImage = (ImageView) rootView.findViewById(R.id.ivImage);
        return rootView;
    }
    public void Notification(){
        NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(getContext())
                .setDefaults(NotificationCompat.DEFAULT_ALL)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.mipmap.ic_launcher))
                .setContentTitle("C4Growth")
                .setContentText("Alerta bullying activada");
        NotificationManager notificationManager = (NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(1,notificationBuilder.build());
    }


    public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults){
        switch (requestCode){
            case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
                if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
                    if(userChoosenTask.equals("Realizar una foto")){
                        cameraIntent();
                    }else if(userChoosenTask.equals("Selecciona una imagen")){
                        galleryIntent();
                    }
                }else{

                }
                break;
        }
    }
    public void onActivityResult(int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode,resultCode,data);
        if(requestCode == Activity.RESULT_OK){
            if(requestCode == SELECT_FILE){
                onSelectFromGalleryResult(data);
            }else if(requestCode == REQUEST_CAMERA){
                onCaptureImageResult(data);
            }
        }
    }

}

我一直在看你的代码!在这里你可以用它做什么!完成任务!

第 1 步: 重写 onActvityCreated() 的方法并在那里使用点击侦听器并使用父级的上下文 activity 在片段中获取其 onActivityResult 方法,这样就可以了!

也检查这个 Stack thread 它有很好的解决方案,我正试图告诉它!

第 2 步:

要了解更多信息,请查看此博客,我发现它有点帮助 blog link 此功劳归于 "Rex St. John"

NOTE : 试试这个,如果不行请在评论中留言,我会试着和你一起解决^_^