First of all get the Width of Screen which may give you limit till where you can translate X
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
Include Random()
to get the random translation from the maximum width of screen.
Random r = new Random();
int translationX = r.nextInt(width)
Use these random generated in translating your view.
public void onClick(View v) {
...
ObjectAnimator anim = ObjectAnimator.ofFloat(imagebutton1, translationX, 100f, 100f);
}
Translating view over your screen.
You can get the view current position with it's getLeft()
, getRight()
, getTop()
and getBottom()
. Use these combination to get the view current position and translate from current position to new random position which is within the screen.
DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;
int height = displaymetrics.heightPixels;
Random r = new Random();
int translationX = r.nextInt(width);
int translationY = r.nextInt(height)
TranslateAnimation anim = new TranslateAnimation( currentX, translationX , currentY, translationY ); //Use current view position instead of `currentX` and `currentY`
anim.setDuration(1000);
anim.setFillAfter(true);
Apply animation on View
which you can post with Handler on schedule interval of time.
view.startAnimation(anim);