How to make a Button randomly Move

后端 未结 2 454
不知归路
不知归路 2021-01-15 00:26

I have a question about how to make a button randomly move every second.

The black tiles are a button:

So I want to make it move randomly in every seco

2条回答
  •  野的像风
    2021-01-15 01:16

    Activity onCreate use this code

     Button button = (Button)findViewById(R.id.my_button);
    

    Create method

       public void buttonmove()
      {
      RelativeLayout .LayoutParams absParams = (RelativeLayout .LayoutParams)button.getLayoutParams();
      DisplayMetrics displaymetrics = new DisplayMetrics();
      getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
      int width = displaymetrics.widthPixels;
      int height = displaymetrics.heightPixels;
      Random r = new Random();
      absParams.x =  r.nextInt(width) ;
      absParams.y =  r.nextInt(height);
      button.setLayoutParams(absParams);
          }                 
    

    if you want in particular time use Timer

     Timer t=new Timer();
    t.schedule(new TimerTask() {
    public void run() {
      buttonmove();//call method
    }
     }, new SimpleDateFormat("HH:mm:ss").parse("13:40:20"));//set time here    
    

提交回复
热议问题