Hnib
Hnib

Reputation: 133

How to set random TextView's position inside linear layout?

I have a linearlayout on xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rootlayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

</LinearLayout>

And I add dynamic 100 textviews inside it by code below:

        llayout = (LinearLayout) findViewById(R.id.rootlayout);

        for (int i = 0; i < 100; i++) {
            TextView tv = new TextView(this);
            tv.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, 
                                                LayoutParams.WRAP_CONTENT));
            int randomInt = new Random().nextInt(100) +1 ;
            tv.setText(""+randomInt);       
            llayout.addView(tv);
        }

The result is 100 textviews added and display vertically. This is not as my expect. I want these textviews display with random position inside the layout look like the image below: enter image description here

How to do it? Thank you!

Upvotes: 4

Views: 2008

Answers (2)

Ridcully
Ridcully

Reputation: 23655

LinearLayout is for layouting its children linearly (as the name suggests).

As there is no RandomLayout, you can use a RelativeLayout with random left and top layout margins, or an AbsoluteLayout and set random x and y.

Edit: Avoid overlapping texts

Random positions can of course lead to overlapping and it would be up to you to adjust the positions or ignore positions too similar to previous ones. Or you might actually compare the bounding boxes (left, top, width, height) of the view you're about to add to all other views in the container and if there is any overlapping, find another place for it.

Upvotes: 3

Santosh
Santosh

Reputation: 169

You can use tv.setX(position) and tv.setY(position) for show view on specific position

Upvotes: 2

Related Questions