如何在Android Object Animator上获得随机数

问题描述 投票:1回答:4

大家好,我正在尝试在我的对象动画师中获取随机数。我想获得“ TranslationX”的随机数`

           imagebutton1.setOnClickListener(new OnClickListener() {

        public void onClick(View arg0) {
           counter++;
            final TextView score = (TextView)findViewById(R.id.textView1);
            score.setText("Score:"+counter);

            ObjectAnimator anim = ObjectAnimator.ofFloat(imagebutton1, "translationX", 100f, 100f);


            anim.setDuration(3600);
            anim.start();;
            anim.setInterpolator(new AccelerateDecelerateInterpolator());
            anim.setRepeatMode(Animation.REVERSE);
            anim.setRepeatCount(5);`
android android-animation
4个回答
1
投票

首先获得屏幕的宽度,这可能会限制您直到可以translate X的位置

DisplayMetrics displaymetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
int width = displaymetrics.widthPixels;

包括Random()以从屏幕的最大宽度获得随机翻译。

Random r = new Random();
int translationX = r.nextInt(width)

使用这些随机数来翻译您的视图。

public void onClick(View v) {
       ...
        ObjectAnimator anim = ObjectAnimator.ofFloat(imagebutton1, translationX, 100f, 100f);
 }

在屏幕上平移视图。

您可以通过getLeft()getRight()getTop()getBottom()获得视图当前位置。使用这些组合可以获得视图的当前位置,并将当前位置转换为屏幕内的新随机位置。

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

View上应用动画,您可以按计划的时间间隔与Handler一起发布。

 view.startAnimation(anim);

0
投票
Random rand = new Random();

int  n = rand.nextInt(50) + 1;

其中nextInt值为最大值,因此在此示例中为1至50


0
投票

首先,导入课程

import java.util.Random;

然后创建一个随机数发生器:

Random r = new Random();

然后用各种next ...方法调用随机发生器。例如,

int locX = r.nextInt(600) + 50;
int locY = r.nextInt(1024) + 50;

随机化器会在0到1(包括0,但不包括1)的范围内创建一个伪随机数。当您调用nextFloat或nextInt方法时,它将此随机数乘以参数,然后将结果强制为适当的类型。

http://developer.android.com/reference/java/util/Random.html处查看随机化器的详细信息


0
投票

但这不是在屏幕上移动文本,如何在各个方向上随机移动文本

© www.soinside.com 2019 - 2024. All rights reserved.