Suppose I have n Button s. And I have to arrange them on the screen in a random order. They should not intersect or cover each other. After a little search for an answer, I found a solution here. But this did not help me much. Here 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 a lot of buttons are hidden outside the screen or intersect at all. How to solve this kind of problem?
And also tried this method. But not all buttons are visible.
protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); LinearLayout l = (LinearLayout)findViewById(R.id.root) ; DisplayMetrics displaymatrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displaymatrics); Log.d("tag" , "width and height: " + displaymatrics.widthPixels + " " + displaymatrics.heightPixels) ; for(int i = 1 ; i<=10 ; i++) { Button b = new Button(this) ; b.setText(i+" "); b.setLayoutParams(new LinearLayout.LayoutParams(dpToPx(65),dpToPx(65))); Random R = new Random(); int dx = R.nextInt(displaymatrics.widthPixels - dpToPx(65)) ; int dy = R.nextInt(displaymatrics.heightPixels - dpToPx(65)); Log.d("tag","dx,dy:" + " " + dx + " " + dy ) ; b.animate().x(dx).y(dy).setDuration(0).start(); l.addView(b); } }
displaymatrics.widthPixels = 720; displaymatrics.heightPixels = 1280;displaymatrics.widthPixels = 720; displaymatrics.heightPixels = 1280;Following the advice of @Asidert, he did as he and all the generated numbers are less than the parameters on top. But many buttons are not visible. Why? - abay