从图库中选择多个图像并在网格视图中显示它们

时间:2015-09-09 06:26:27

标签: android android-gridview

我想从图库中选择多个图像并在gridview中显示它们,但我没有得到正确的结果。如果我从图库中选择一个图像然后它会在gridView中显示,但是当我从图库中选择多个图像时我会遇到异常。 源代码如下。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
Button camera_click, gallery_btn;
GridView grid;
static final int REQUEST_IMAGE_CAPTURE = 1;
ArrayList<String> imagesPathList;
public static final String gridview_image_path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GalleryPic/";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    camera_click = (Button) findViewById(R.id.camera_click);
    gallery_btn = (Button) findViewById(R.id.gallery_button);
    grid = (GridView) findViewById(R.id.gridView);
    //imageView = (ImageView)findViewById(R.id.image);
    camera_click.setOnClickListener(this);
    openGallery();
}


public void openGallery() {
    gallery_btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.setType("image/*");
            intent.setAction(Intent.ACTION_GET_CONTENT);
            intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
            startActivityForResult(Intent.createChooser(intent, "Select Picture"), REQUEST_IMAGE_CAPTURE);

        }
    });
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    try {
        // When an Image is picked
        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK
                && null != data) {
            // Get the Image from data

            imagesPathList = new ArrayList<String>();
            String[] imagesPath = data.getStringExtra("data").split("\\|");

            for (int i = 0; i < imagesPath.length; i++) {
                imagesPathList.add(imagesPath[i]);
            }
            grid.setAdapter(new ImageListAdapter(this, imagesPathList));

        } else {
            Toast.makeText(this, "You haven't picked Image",
                    Toast.LENGTH_LONG).show();
        }
    } catch (Exception e) {
        Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG)
                .show();
    }

}

public class ImageListAdapter extends BaseAdapter {

    private Context context;
    private List<String> imgpic;

    public ImageListAdapter(Context c, List<String> thpic) {
        context = c;
        imgpic = thpic;
    }

    @Override
    public int getCount() {
        if (imgpic != null) return imgpic.size();
        else
            return 0;
    }

    @Override
    public Object getItem(int position) {
        return position;
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ImageView imageView;

        BitmapFactory.Options bf_option = new BitmapFactory.Options();

        bf_option.inDither = false;
        bf_option.inPurgeable = true;
        bf_option.inInputShareable = true;
        bf_option.inTempStorage = new byte[32 * 1024];
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setPadding(0, 0, 0, 0);
        } else {
            imageView = (ImageView) convertView;
        }
        FileInputStream fs = null;
        Bitmap bm;
        try {
            fs = new FileInputStream(new File(imgpic.get(position).toString()));

            if (fs != null) {
                bm = BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bf_option);
                // bm = BitmapFactory.decodeFile(_path)
                imageView.setImageBitmap(bm);
                imageView.setId(position);
                imageView.setLayoutParams(new GridView.LayoutParams(400, 300));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (fs != null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imageView;
    }
    //return null;
}


@Override
public void onClick(View v) {
    if (v.getId() == R.id.camera_click) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException e) {
                //e.printStackTrace();
                Toast.makeText(MainActivity.this, "File creation problem", Toast.LENGTH_LONG).show();
            }
            if (photoFile != null) {
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
            }
        } else {
            Toast.makeText(MainActivity.this, "Capture Intent Problem", Toast.LENGTH_LONG).show();
        }
    }
}


private File createImageFile() throws IOException {
    // Create an image file name
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
    String imageFileName = "JPEG_" + timeStamp + "_";
    //File storageDir = Environment.getExternalStoragePublicDirectory(
    //      Environment.DIRECTORY_PICTURES);
    File storageDir = new File(gridview_image_path);
    storageDir.mkdirs();
    File image = File.createTempFile(
            imageFileName,  /* prefix */
            ".jpg",         /* suffix */
            storageDir      /* directory */
    );

    // mCurrentPhotoPath = image.getAbsolutePath();
    //mCurrentPhotoPath = gridview_image_path + imageFileName+".jpg";
    return image;
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

0 个答案:

没有答案