【问题标题】:get a random picture from phone gallery and display in view从手机图库中获取随机图片并显示在视图中
【发布时间】:2013-06-12 19:49:16
【问题描述】:

是否可以访问手机图库,选择随机图像并将其显示在视图上?即整个过程无需用户干预即可完成,无需选择图像或发送 uri 等。

谢谢!

【问题讨论】:

  • 一定要及时奖励他们的回应,例如下面的黑带。否则,糟糕的声誉将付诸东流,没有人会受益sadface

标签: android bitmap gallery


【解决方案1】:

以下 sn-p 检索图库的内容并将每个图像路径放入数组列表中。然后它随机选择 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);
        }
    });

}

【讨论】:

  • 我还没来得及检查这个,但 8 人赞成说代码有效,所以赏金是你的 :) 非常感谢您的帮助!
  • 很好的答案,但现在代码需要一些更改。光标需要关闭 cur.close(); 并且 managedQuery 现在已弃用。应该是Cursor cur = getContentResolver().query(images, projection, null, null, null);
  • @cyborg86pl 感谢您的意见。我同意cursor.close(),但我为什么要更改查询?仍然记得 sn-p 是一个工作示例,但仍然是一个示例。由 OP 做出正确的更正。
  • 我不是说它不起作用,它只是更新了stackoverflow.com/a/17739957/1413151
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-27
  • 1970-01-01
相关资源
最近更新 更多