How to pick an image from gallery (SD Card) for my app?

前端 未结 10 1885
Happy的楠姐
Happy的楠姐 2020-11-21 23:40

This question was originally asked for Android 1.6.

I am working on photos options in my app.

I have a button and an ImageView in my Activity. When I click

10条回答
  •  忘掉有多难
    2020-11-22 00:21

    call chooseImage method like-

    public void chooseImage(ImageView v)
    {
        Intent intent = new Intent(Intent.ACTION_PICK);
        intent.setType("image/*");
        startActivityForResult(intent, SELECT_PHOTO);
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
    
        if(imageReturnedIntent != null)
        {
            Uri selectedImage = imageReturnedIntent.getData();
        switch(requestCode) { 
        case SELECT_PHOTO:
            if(resultCode == RESULT_OK)
            {
                Bitmap datifoto = null;
                temp.setImageBitmap(null);
                Uri picUri = null;
                picUri = imageReturnedIntent.getData();//<- get Uri here from data intent
                 if(picUri !=null){
                   try {
                       datifoto = android.provider.MediaStore.Images.Media.getBitmap(this.getContentResolver(),                                 picUri);
                       temp.setImageBitmap(datifoto);
                   } catch (FileNotFoundException e) {
                      throw new RuntimeException(e);
                   } catch (IOException e) {
                      throw new RuntimeException(e);
                   } catch (OutOfMemoryError e) {
                    Toast.makeText(getBaseContext(), "Image is too large. choose other", Toast.LENGTH_LONG).show();
                }
    
            }
            }
            break;
    
    }
        }
        else
        {
            //Toast.makeText(getBaseContext(), "data null", Toast.LENGTH_SHORT).show();
        }
    }
    

提交回复
热议问题