2014-03-02 41 views
1

你好家伙我想要在我的对象动画师中得到随机数。 我想获得的随机数为 “TranslationX” `如何获得Android对象动画师的随机数

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

回答

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动画,你可以与处理器张贴的时间表间隔。

view.startAnimation(anim); 
+0

我的代码现在采取只X方向的随机数我可以让X和Y在1函数? – Boldbayar

+0

@Boldbayar:翻译视图需要你使用'TranslateAnimation'。请编辑答案 –

0
Random rand = new Random(); 

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

其中nextInt值是最大值,所以在这个例子中的,从1- 50

+0

哇,先生你救了我的一天我想知道我是否可以在该行使用它,但它的作品谢谢你帮助先生。分享是关怀我试图帮助像你这样的人^^。 – Boldbayar

+0

接受我的答案..这将是关怀;) – MDMalik

0

首先,导入类

import java.util.Random; 

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

Random r = new Random(); 

然后用各种next方法调用randomizer。例如,

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