How To Get Random Number On Android Object Animator
Solution 1:
First of all get the Width of Screen which may give you limit till where you can translate X
DisplayMetricsdisplaymetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
intwidth= displaymetrics.widthPixels;
Include Random()
to get the random translation from the maximum width of screen.
Randomr=newRandom();
inttranslationX= r.nextInt(width)
Use these random generated in translating your view.
publicvoidonClick(View v) {
...
ObjectAnimatoranim= 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.
DisplayMetricsdisplaymetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
intwidth= displaymetrics.widthPixels;
intheight= displaymetrics.heightPixels;
Randomr=newRandom();
inttranslationX= r.nextInt(width);
inttranslationY= r.nextInt(height)
TranslateAnimationanim=newTranslateAnimation( 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);
Solution 2:
Randomrand=newRandom();
intn= rand.nextInt(50) + 1;
where nextInt
value is the Maximum value so in this example its from 1- 50
Solution 3:
First, import the class
import java.util.Random;
Then create a randomizer:
Randomr=newRandom();
Then call the randomizer with the various next... methods. For example,
int locX = r.nextInt(600) + 50;
int locY = r.nextInt(1024) + 50;
The randomizer creates a pseudo-random number in the range of 0 to 1 (including 0, but not including 1). When you call the nextFloat or nextInt method, it multiplies this random number by the parameter and then coerces the result into the appropriate type.
See details of the randomizer at http://developer.android.com/reference/java/util/Random.html
Post a Comment for "How To Get Random Number On Android Object Animator"