How To Make A Button Randomly Move
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 second or more fast. this is my
Solution 1:
First you should get the screen size
publicstatic Point getDisplaySize(@NonNull Context context) {
Pointpoint=newPoint();
WindowManagermanager= (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
privatevoidsetButtonRandomPosition(Button button){
int randomX = newRandom().nextInt(getDisplaySize(this).x);
int randomY = newRandom().nextInt(getDisplaySize(this).y);
button.setX(randomX);
button.setY(randomY);
}
Finally to make this happen every second
privatevoidstartRandomButton(Button button) {
Timer timer = newTimer();
timer.schedule(newTimerTask() {
@Overridepublicvoidrun() {
setButtonRandomPosition(button);
}
}, 0, 1000);//Update button every second
}
In on create run it like this
@OverrideprotectedvoidonCreate(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);
}
Solution 2:
Activity onCreate use this code
Buttonbutton= (Button)findViewById(R.id.my_button);
Create method
publicvoidbuttonmove()
{
RelativeLayout .LayoutParamsabsParams= (RelativeLayout .LayoutParams)button.getLayoutParams();
DisplayMetricsdisplaymetrics=newDisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
intwidth= displaymetrics.widthPixels;
intheight= displaymetrics.heightPixels;
Randomr=newRandom();
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() {
publicvoidrun() {
buttonmove();//call method
}
}, new SimpleDateFormat("HH:mm:ss").parse("13:40:20"));//set time here
Post a Comment for "How To Make A Button Randomly Move"