我想在随机位置创建10个ImageViews
,我希望它们是相同的,我尝试使用ImageView[]
,我得到了屏幕尺寸(宽度和高度)并为每个创建了随机位置ImageView
(在屏幕大小范围内)。有些ImageViews
超出范围,因为有时我会看到7,8 ImageViews
。这是我的代码:
ImageView ball[], you;
int layoutwidth, layoutheight;
Random rand = new Random();
RelativeLayout rlt;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rlt = (RelativeLayout) findViewById(R.id.rlt);
you = (ImageView) findViewById(R.id.imageView);
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
layoutwidth = size.x;
layoutheight = size.y;
ball = new ImageView[11];
for (int i = 0; i < 10; i++) {
ball[i] = new ImageView(this);
ball[i].setTag(i);
ball[i].setBackgroundResource(R.mipmap.ball);
int randomx = rand.nextInt(layoutwidth+1);
int randomy = rand.nextInt(layoutheight+1);
ball[i].setX(randomx);
ball[i].setY(randomy);
rlt.addView(ball[i]);
}
}
如何根据需要使代码正常工作?
答案 0 :(得分:0)
您可以尝试替换此
int randomx = rand.nextInt(layoutwidth+1);
int randomy = rand.nextInt(layoutheight+1);
ball[i].setX(randomx);
ball[i].setY(randomy);
rlt.addView(ball[i]);
与
int randomx = rand.nextInt(layoutwidth+1-widthOfImageView);
int randomy = rand.nextInt(layoutheight+1-heightOfImageView);
rlt.addView(ball[i]);
ball[i].setTranslationX(randomx);
ball[i].setTranslationY(randomy);
其中 widthOfImageView,heightOfImageView 是imageview&#39;的宽度&amp;高度