Let I have n
Buttons. And I need to put them on screen randomly. They don't have to overlay each other. And also they don't have to be putted outside of the screen. After the little search I've found a way to achieve it here
Below is my code:
setContentView(R.layout.activity_main);
LinearLayout l = (LinearLayout)findViewById(R.id.root) ;
DisplayMetrics displaymatrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displaymatrics);
for(int i = 1 ; i<=n ; i++) {
Button b = new Button(this) ;
b.setText("A");
b.setLayoutParams(new LinearLayout.LayoutParams(dpToPx(65),dpToPx(65)));
Random R = new Random();
float dx = R.nextFloat() * displaymatrics.widthPixels;
float dy = R.nextFloat() * displaymatrics.heightPixels;
b.animate().x(dx).y(dy).setDuration(0).start();
l.addView(b);
}
}
private int dpToPx(int dp) {
return (int) (dp * Resources.getSystem().getDisplayMetrics().density);
}
But the problem is that some buttons are hidden outside of the screen. How to solve this problem? And after this, how buttons cannot be overlayed each other?