从手机图库中获取随机图片并在视图中显示

时间:2013-06-12 19:49:17

标签: android bitmap gallery

是否有可能访问电话库,选择随机图像并在视图上显示?即在没有用户干预的情况下完成整个过程,必须选择图像或发送uri等等。

谢谢!

1 个答案:

答案 0 :(得分:18)

以下代码段检索图库的内容,并将每个图像路径放在数组列表中。然后它随机选择ArrayList中的一个路径并将其作为ImageView的资源

Handler handler = new Handler();

protected int counter = 0;
private ImageView mImageView;
private Bitmap currentBitmap = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.image);
    mImageView = (ImageView) findViewById(R.id.imageView);
    String[] projection = new String[]{
            MediaStore.Images.Media.DATA,
    };

    Uri images = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
    Cursor cur = managedQuery(images,
            projection,
            "",
            null,
            ""
    );

    final ArrayList<String> imagesPath = new ArrayList<String>();
    if (cur.moveToFirst()) {

        int dataColumn = cur.getColumnIndex(
                MediaStore.Images.Media.DATA);
        do {
            imagesPath.add(cur.getString(dataColumn));
        } while (cur.moveToNext());
    }
    cur.close();
    final Random random = new Random();
    final int count = imagesPath.size();
    handler.post(new Runnable() {
        @Override
        public void run() {
            int number = random.nextInt(count);
            String path = imagesPath.get(number);
            if (currentBitmap != null)
                currentBitmap.recycle();
              currentBitmap = BitmapFactory.decodeFile(path);
            mImageView.setImageBitmap(currentBitmap);
            handler.postDelayed(this, 1000);
        }
    });

}