对不起大家我是android编程的新手。
我有一个游戏,它包含数组中的图像数量。我想在4个图像视图中显示3个相同的图像和1个不同的图像,如果答案是正确的并且玩家找到不同的图像,它将再次循环和随机。请有人给我提供一个例子。
Random random = new Random( System.currentTimeMillis() );
int next = random.nextInt( 23 ) + 1;
int[] imageViews = {R.id.A,R.id.B,R.id.C,R.id.D };
int[] img = new int[] {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,
R.drawable.img5,R.drawable.img6,R.drawable.img7,R.drawable.img8,
R.drawable.img9,R.drawable.img10};
int [] ansImg = new int[]{R.drawable.aimg1,R.drawable.aimg2,R.drawable.aimg3,R.drawable.aimg4,
R.drawable.aimg5,R.drawable.aimg6,R.drawable.aimg7,R.drawable.aimg8,
R.drawable.aimg9,R.drawable.aimg10};
private void allImage() {
ImageView a= (ImageView)findViewById(R.id.A);
ImageView b= (ImageView)findViewById(R.id.B);
ImageView c= (ImageView)findViewById(R.id.C);
ImageView d= (ImageView)findViewById(R.id.D);
}
public void randomImage(){
List<Integer> generated = new ArrayList<Integer>();
for (int i = 0; i < imageViews.length; i++) {
int v = imageViews[i]-1;
int vs = imageViews[i]-3;
if ( generated.contains( next ) ) {
generated.add( next );
ImageView iv = (ImageView) findViewById( v );
ImageView ivs = (ImageView) findViewById( vs );
iv.setImageResource( img[next] );
ivs.setImageResource(ansImg[next]);
}
}
}
答案 0 :(得分:0)
确定,
首先,保持对你正在使用的ImageView的引用,并在每次循环时使用findViewById,因为这是浪费时间,因为它很昂贵。
这将为您提供视图id-3,
int vs = imageViews[i]-3;
所以如果你打电话
ImageView ivs = (ImageView) findViewById( vs );
ivs它可能是null,或者是与列表中的i-3rd不同的View。
此代码将为3个随机ImageView显示相同的randomImage,并将另一个数组的randomImage设置为最后一个ImageView
Random random = new Random( System.currentTimeMillis() );
ImageView[] imageViews = new ImageView[4];
int[] img = new int[] {R.drawable.img1,R.drawable.img2,R.drawable.img3,R.drawable.img4,
R.drawable.img5,R.drawable.img6,R.drawable.img7,R.drawable.img8,
R.drawable.img9,R.drawable.img10};
int [] ansImg = new int[]{R.drawable.aimg1,R.drawable.aimg2,R.drawable.aimg3,R.drawable.aimg4,
R.drawable.aimg5,R.drawable.aimg6,R.drawable.aimg7,R.drawable.aimg8,
R.drawable.aimg9,R.drawable.aimg10};
private void allImage() {
imageViews[0]= (ImageView)findViewById(R.id.A);
imageViews[1]= (ImageView)findViewById(R.id.B);
imageViews[2]= (ImageView)findViewById(R.id.C);
imageViews[3]= (ImageView)findViewById(R.id.D);
}
public void randomImage(){
// List<Integer> generated = new ArrayList<Integer>(); i dont get what that is supposed to do?
int next = random.nextInt( img.length+1 ); // will generate a position from a random image within the img array
int randomOtherImage = random.nextInt( ansImg.length+1 );
int differentImage = random.nextInt( imageViews.length+1 );
for (int i = 0; i < imageViews.length; i++) {
if (differentImage == i)
imageViews[i].setImageRessource(ansImg[randomOtherImage]);
else
imageViews[i].setImageRessource(ans[next]);
}
}