How to make a Button randomly Move

后端 未结 2 469
不知归路
不知归路 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:19

    First you should get the screen size

    public static Point getDisplaySize(@NonNull Context context) {
        Point point = new Point();
        WindowManager manager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        manager.getDefaultDisplay().getSize(point);
        return point;
    }
    

    Then you should get a random x and random y position for the button to go to so that its still on screen

    private void setButtonRandomPosition(Button button){
        int randomX = new Random().nextInt(getDisplaySize(this).x);
        int randomY = new Random().nextInt(getDisplaySize(this).y);
    
        button.setX(randomX);
        button.setY(randomY);
    }
    

    Finally to make this happen every second

    private void startRandomButton(Button button) {
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                setButtonRandomPosition(button);
            }
        }, 0, 1000);//Update button every second
    }
    

    In on create run it like this

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.tested);
    
    
        buttonblack = (Button)findViewById(R.id.black1);
    
        startRandomButton(blackbutton);
    }
    

提交回复
热议问题