0

I am developing an app that requires multiple buttons to be created dynamically (onCreate of MainActivity class). Each button has a dimension of 100x100dp.

Here's the code:

    for (int i = 0; i < count; i++) {
        buttons[i] = new Button(this);
        RelativeLayout ll = (RelativeLayout)findViewById(R.id.maincontainer);
        RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        buttons[i].setY(i * 150); // should be random
        buttons[i].setX(i * 120); // should be random
        String temp = Character.toString(input.charAt(i));
        buttons[i].setText(temp);
        buttons[i].setOnClickListener(this);
        buttons[i].setId(i);
        test1.setText(Integer.toString(buttons[i].getId()));

        ll.addView(buttons[i],lp);
    }

The position of these buttons should be completely random within the layout which can be easily achieved by generating random values for x and y coordinates. But I need the buttons not to overlap other buttons. Also due to 100x100dp dimension, sometimes the previously generated buttons are being partially overlapped by new ones.

Zoe
  • 27,060
  • 21
  • 118
  • 148
Saurav
  • 96
  • 1
  • 5

1 Answers1

0

You can actually figure this out programatically. Keep the co-ordinates of the views that you generate stored in a list. Then simply compare the co-ordinates to see if the new view intersects. You can use the following for a visualisation:

http://silentmatt.com/rectangle-intersection/

I hope you try writing code than copying it from someplace. :)

A SO link to help you out: Determine if two rectangles overlap each other?

Community
  • 1
  • 1
Codester
  • 193
  • 6
  • Thanks @codester . This is exactly what I thought as a last resort.Flow layout seems interesting but will now go with your approch. Cheers! – Saurav Oct 29 '15 at 09:07