【发布时间】:2013-06-12 19:49:16
【问题描述】:
是否可以访问手机图库,选择随机图像并将其显示在视图上?即整个过程无需用户干预即可完成,无需选择图像或发送 uri 等。
谢谢!
【问题讨论】:
-
一定要及时奖励他们的回应,例如下面的黑带。否则,糟糕的声誉将付诸东流,没有人会受益sadface。
是否可以访问手机图库,选择随机图像并将其显示在视图上?即整个过程无需用户干预即可完成,无需选择图像或发送 uri 等。
谢谢!
【问题讨论】:
以下 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);
}
});
}
【讨论】:
cur.close(); 并且 managedQuery 现在已弃用。应该是Cursor cur = getContentResolver().query(images, projection, null, null, null);
cursor.close(),但我为什么要更改查询?仍然记得 sn-p 是一个工作示例,但仍然是一个示例。由 OP 做出正确的更正。