How To Display Random images on image view(如何在图像视图上显示随机图像)
问题描述
有人可以帮我提供一个代码来随机显示我的绘图文件夹中的图片吗?我是java新手,所以我不知道该怎么做.任何帮助将不胜感激.我的要求是:-1.显示随机图像(图像应在每次启动时改变)2.就是这样
Could someone please help me out with a code to randomly display a picture from the my drawings folder? i am new to java so i have no idea how to do it. Any help will be appreciated. My Requirements are:- 1.Display Random image (image should change on each start up) 2.that's all
推荐答案
将一些名为 img_0 到 img_n 的图片放到你的 res/drawable 文件夹中
Put some images named img_0 to img_n in your res/drawable folder
布局(res/layout/rnd_images.xml):
Layout (res/layout/rnd_images.xml):
代码:
请注意,您必须将 rnd.nextInt(2) 设置为 rnd.nextInt(Max - 1),因为 rnd 从 0 开始
Note that you have to set rnd.nextInt(2) to rnd.nextInt(Max - 1), since rnd starts from 0
[更新]
布局名称必须与 setContentView 中的名称匹配.
所以,如果你有(为什么?)这个:
The layout name must match that in setContentView.
So, if you have (why?) this:
在您的 MainActivity.java/onCreate 中,然后将布局重命名为activity_main.xml"
in your MainActivity.java/onCreate, then rename the layout "activity_main.xml"
或者,更好的是,按原样使用我的代码.
OR, better, USE MY CODE AS IS.
无需修改即可工作.
[更新]
检查这一行:
它需要以下导入:
我的代码按原样工作.我在给你之前测试了它.
只需将我的布局放在 res/layout 中,将图像放在 res/drawable 和 MainActivity.java 中即可替换默认的.
My code works as is. I tested it before giving it to you.
Just place my layout in res/layout, the images in res/drawable and the MainActivity.java to replace the default one.
请注意,图片名称必须是img_#",其中 # 是一个数字.
此数字必须为 0 到 (max - 1).
Please, notice that the images names MUST be "img_#" where # is a number.
This number must be 0 to (max - 1).
或者给出诸如my_city_#"之类的名称.
但随后您必须更新 java 代码以匹配这些名称.
Or give names like "my_city_#" or whatever.
But then you must update the java code to match these names.
这篇关于如何在图像视图上显示随机图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!