我正在尝试使用Timer和Random类使球图像在relativeLayoutGame布局中随机移动。请您帮忙我如何确保球在布局内保持移动(不要离开它)。
public void hide(View view){
final Timer tmr = new Timer();
final ImageView imgBall = (ImageView)findViewById(R.id.imgBall);
final RelativeLayout relativeLayGame = (RelativeLayout)findViewById(R.id.relativeLayGame);
final float gameLayoutWidth = relativeLayGame.getWidth();
final float gameLayoutHeiht = relativeLayGame.getHeight();
tmr.schedule(
new TimerTask() {
@Override
public void run() {
Random rnd = new Random();
int xRnd = rnd.nextInt(996)-996;
int yRnd = rnd.nextInt(1358)-1358;
if(xRnd == gameLayoutWidth || yRnd == gameLayoutHeiht){
xRnd = rnd.nextInt(996)-996;
yRnd = rnd.nextInt(1358)-1358;
imgBall.animate().xBy(xRnd).yBy(yRnd);
}else {
imgBall.animate().xBy(xRnd).yBy(yRnd);
}
}
},0,2000
);
}