如何控制图像离开屏幕(使用计时器和随机)Android

时间:2016-06-15 00:12:06

标签: java android android-studio random timer

我正在尝试使用Timer和Random类使球图像在relativeLayoutGame布局中随机移动。请您帮忙我如何确保球在布局内保持移动(不要离开它)。

enter image description here

    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
    );



}

0 个答案:

没有答案