user458753
user458753

Reputation: 147

Best way to add imageviews to layout at random location

Question says it all, i have 52 imageviews(deck of cards) that i wanna show in random positions.

i currently have this:

for (Card card : deck.getAll()) {
        ImageView iv = new ImageView(this);
        RelativeLayout.LayoutParams lParams = new RelativeLayout.LayoutParams(57, 105);
        if (random) {
            lParams.leftMargin = (int)Math.ceil(Math.random()*(metrics.widthPixels - 57));
            lParams.topMargin = (int)Math.ceil(Math.random()*(metrics.heightPixels - 105));
        } else {
            //if (metrics.widthPixels < ((i + 1) * 57)) {i = 0;++j;}
            if (i > 12) {i = 0;++j;}
            lParams.leftMargin = i*60; 
            lParams.topMargin  = j*107;
            ++i;
        }
        iv.setRotation((float)Math.ceil(Math.random()*(360)));
        iv.setId(card.getInt());

        layout.addView(iv, lParams);

This works for now, but later on i will have to display all cards in specific locations and it just dont seem right to me positioning everything with the margins.

Thanks in advance for any and all advice!

Upvotes: 2

Views: 1930

Answers (1)

Zulaxia
Zulaxia

Reputation: 2742

Go read about using a Canvas and drawing the bitmaps direct to that. You put one View in to render to, and then implement the onDraw of that to render your cards to the canvas of that one View.

Every time a card needs moved, you redraw the Canvas, and don't need to otherwise. It's basically how 2d games work. There are lots of tutorials and it doesn't take long at all.

Upvotes: 1

Related Questions