【问题标题】:Can't replace image view, for image from a camera or gallery (It doesn't work)无法替换图像视图,用于来自相机或画廊的图像(它不起作用)
【发布时间】:2018-10-08 23:49:23
【问题描述】:

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

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

}

【问题讨论】:

  • 从您的代码中我可以看到您正在尝试获取图片,然后将其保存在图库中,然后重新获取它以用于 ImageView!你能分享更多代码或logcat错误吗?请。
  • 我有一个建议的解决方案,您正在获取正确的数据!那里没有错误,但您正在尝试将图像从 imageResult 获取到您的片段!我可以看到您在 Fragment 的 View 方法中使用了单击侦听器!可行,但您应该尝试在片段的 ONACTIVITYCREATED 方法中使用您的点击代码
  • 在 logcat 中我没有看到任何重要错误,当我从我的画廊中选择了正确选择但没有替换旧照片的照片时,我想替换这个片段中的照片,如何我能解决吗?如果我在 oncreate 中尝试我的替换点击代码,应用程序崩溃@rizwan-atta
  • 覆盖片段中名为“onActivityCreated”的另一个方法,并将点击监听器放在那里并重试
  • 我的片段调用 onActivityCreated 中没有任何方法,只有 onCreated 和 onCreatedView :( @rizwan-atta,我把这个方法放在哪里?

标签: android android-camera android-gallery


【解决方案1】:

我一直在查看您的代码!在这里你可以用它做什么!把事情做好!

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

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

第 2 步:

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

注意 :试试这个,如果这不起作用,请进入 cmets,我会尝试与您一起解决 ^_^

【讨论】:

  • 我打算遵循解决方案,但我的片段仍然无法正常工作:( @rizwan-atta
  • 在我有 startActivityForResult(intent, REQUEST_CAMERA); 之前,我在 cameraintent() 和 galleryintent() 中更改了一些代码现在我有 frag.startActivityForResult(intent,REQUEST_CAMERA);我没有发现错误:(@rizwan-atta
猜你喜欢
  • 2017-02-25
  • 2013-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
相关资源
最近更新 更多