下面是我写的代码片段。我在背景中有一个大的可滚动图像,在前景中有一个较小的图像。静态地布局对我来说很好。我想要做的是,在5秒的间隔之后,通过更改topMargin和leftMargin来随机化前景图像的新位置。我知道伪随机数生成器可用于更改值。但是,我不知道如何声明我想要更改“params.topMargin”和“params.leftMargin”值或如何在计时器上发生这种情况。
mImage = (ImageView)findViewById(R.id.Image1);
RelativeLayout.LayoutParams params = new
LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.topMargin = 1200;
params.leftMargin = 45;
mImage.setLayoutParams(params);
出于约束的原因,我知道随机数生成器可以预先定义的值范围,我也需要这样做。
如果有人能帮助我指出正确的方向,那就太棒了:D
编辑:我很确定我需要将一个计时器,一个意图和一个getRandom()与另一个结合使用。我不太确定如何将它们正确地放在一起。
答案 0 :(得分:1)
在onCreate方法上试试这个:
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
mImage = (ImageView)YourActivity.this.findViewById(R.id.Image1);
RelativeLayout.LayoutParams params = new
LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.topMargin = (int)(Math.random()*500 + 1); //500 is the max margin, you can change it
params.leftMargin = (int)(Math.random()*500 + 1); //500 is the max margin, you can change it
mImage.setLayoutParams(params);
handler.postDelayed(this, 1000); //1000 is the interval in milliseconds
}
};
r.run();