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

问题描述 投票:9回答:1

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

谢谢!

android bitmap gallery
1个回答
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);
        }
    });

}
© www.soinside.com 2019 - 2024. All rights reserved.