9

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

谢谢!

4

1 回答 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);
        }
    });

}
于 2013-06-16T08:54:20.730 回答