如何从图库中获取图像并在Fragments中设置为图像视图?

时间:2015-02-05 10:11:47

标签: android

我已经编写了用于从图库中获取图像并设置为图像视图但未设置图像的代码。这是我的问题建议我们这些人

这是我的代码:

 btnUpload.setOnClickListener(new View.OnClickListener()
{
            @Override
            public void onClick(View v) 
{
                Intent i = new Intent(Intent.ACTION_PICK,
                  android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                getActivity().startActivityForResult(i, 1);

            }
        });


 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data)
{
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && null != data) 
{
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};

            Cursor cursor = getActivity().getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();

            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            //int pic=Integer.parseInt(picturePath);
            cursor.close();

            //ImageView imageView = (ImageView) mFormView.findViewById(R.id.imageView);
            ivMan.setImageBitmap(BitmapFactory.decodeFile(picturePath));

        }

先谢谢

2 个答案:

答案 0 :(得分:0)

  1. 从图库中获取图片

    Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE);
    
  2. 检查是否有正确的路径,如果是,则解码图像并设置为imageview。

      protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_IMAGE && data != null && data.getData() != null) {
        Uri _uri = data.getData();
    
        //User had pick an image.
        Cursor cursor = getContentResolver().query(_uri, new String[]{android.provider.MediaStore.Images.ImageColumns.DATA}, null, null, null);
        cursor.moveToFirst();
    
        //Link to the image
        final String imageFilePath = cursor.getString(0);
        cursor.close();
        File file = new File(imageFilePath);
        if (file.exists()) {
            Bitmap bMap = decodeFile(file);
            //  asset.setImageBitmap(bMap);
            asset.setImageBitmap(bMap);
        }
    }
    super.onActivityResult(requestCode, resultCode, data);
    

    }

  3. 这将肆无忌惮地帮助你

答案 1 :(得分:0)

替换getActivity()。startActivityForResult(i,1);与
startActivityForResult(i,1);