我是初学者 Android 开发者 在我的应用程序中,我想制作一张随机图像 每次启动应用程序时都会加载图像列表。 一般来说,我想使用 ImageView 因为它很简单, 但是你必须提到在布局文件中加载什么图像或者 主.XML.
我不知道该怎么做,所以请帮忙。 :-)
最佳答案
不需要在.xml文件中设置图片
比如说,你的布局中有一个 ImageView(比如说它的 main.xml)
主.xml
<ImageView>
android:id="@id+/myImageView"
</ImageView>
在您的 Activity 中
int[] images = new int[] {R.drawable.image01, R.drawable.image02, R.drawable.image03};
// Get the ImageView
setContent(R.layout.main);
ImageView mImageView = (ImageView)findViewById(R.id.myImageView);
// Get a random between 0 and images.length-1
int imageId = (int)(Math.random() * images.length);
// Set the image
mImageView.setBackgroundResource(images[imageId]);
希望这有帮助(:
编辑
- 图像数组的索引不应硬编码
- 更正了语法错误。谢谢汤姆指出:)
关于android - 如何在 ImageView 中加载随机图像? (安卓),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20008842/