我试图创建一个生成随机图像的函数,但从不两次,直到没有图像为止。
在我的情况下,有15个图像文件可以绘制,我想让它们全部显示但不重复。
package com.example.commander;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends Activity {
final Random rnd = new Random();
ImageView img = null;
Button btnRandom = null;
@Override
protected void onCreate(
final Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img = (ImageView) findViewById(R.id.imgRandom);
btnRandom = (Button) findViewById(R.id.btnRandom);
}
protected final static int getResourceID
(final String resName, final String resType, final Context ctx)
{
final int ResourceID =
ctx.getResources().getIdentifier(resName, resType,
ctx.getApplicationInfo().packageName);
if (ResourceID == 0)
{
throw new IllegalArgumentException
(
"No resource string found with name " + resName
);
}
else
{
return ResourceID;
}
}
ArrayList<Integer> imageId = new ArrayList<Integer>();
public void clickHandler(final View v)
{
switch(v.getId())
{
case R.id.btnRandom:
{
if (!btnRandom.isEnabled())
{
return;
}
int indeks = rnd.nextInt(14);
final String str = "img_" + indeks;
img.setImageDrawable
(
getResources().getDrawable(getResourceID(str, "drawable",
getApplicationContext())));
}}}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
public void goBack(View v){
startActivity(new Intent(this, MainActivity.class));
}
@Override
public void onBackPressed() {
}
}
答案 0 :(得分:3)
将所有图片ID插入一个列表,使用AndroidWarriors答案生成一个随机数,获取该图像并从列表中删除,调用更多时间,直到列表大小变为0
您可以使用以下代码:
ArrayList<Integer> imageId = new ArrayList<Integer>();
// insert your id here
然后:
int index ;
while (imageId.size() > 0)
{
index = randomInt(0 , imageId.size());
/// do what you want with this index
imageId.remove(index);
}
和randomInt
public int randomInt(int min, int max) {
Random randNumber = new Random();
int randomNumber = randNumber.nextInt((max - min) + 1) + min;
return randomNumber;
}
答案 1 :(得分:0)
您可以通过生成范围内的随机数来选择图像
public int randomInt(int min, int max) {
Random randNumber = new Random();
int randomNumber = randNumber.nextInt((max - min) + 1) + min;
return randomNumber;
}
还将整数ArrayList
维护为类成员变量,并插入从函数接收的int值。设置图像时检查返回的int是否存在于数组中。如果是,则再次调用该函数,如果否,则设置图像,最后当数组长度变为15时停止执行代码。