简体   繁体   English

如何在线性布局中设置随机TextView的位置?

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

I have a linearlayout on xml 我在xml上有一个linearlayout

<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: 我通过以下代码在其中添加动态100个文本视图:

        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. 结果是添加了100个文本视图并垂直显示。 This is not as my expect. 这不是我的期望。 I want these textviews display with random position inside the layout look like the image below: 我希望这些textviews显示在布局中的随机位置,如下图所示: 在此输入图像描述

How to do it? 怎么做? Thank you! 谢谢!

LinearLayout is for layouting its children linearly (as the name suggests). LinearLayout用于线性布局其子节点(顾名思义)。

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. 由于没有RandomLayout ,您可以使用具有随机左侧和顶部布局边距的RelativeLayout ,或者使用AbsoluteLayout并设置随机x和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. 或者,您实际上可能会比较要添加到容器中所有其他视图的视图的边界框(左侧,顶部,宽度,高度),如果有任何重叠,请为其找到另一个位置。

您可以使用tv.setX(位置)和tv.setY(位置)来显示特定位置的视图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM