如何防止重叠TextViews - Android

时间:2016-01-14 21:28:28

标签: java android

当用户触摸其中一个时,我想随机更改文本视图位置,并使用此代码进行管理:

    int leftDistance1 = new Random().nextInt(layoutWidth);
    int leftDistance2 = new Random().nextInt(layoutWidth);
    int leftDistance3 = new Random().nextInt(layoutWidth);

    while(leftDistance1 == leftDistance2)
    {
        leftDistance2 = new Random().nextInt(layoutWidth);
    }
    while(leftDistance1 == leftDistance3)
    {
        leftDistance3 = new Random().nextInt(layoutWidth);
    }
    while(leftDistance2 == leftDistance3)
    {
        leftDistance3 = new Random().nextInt(layoutWidth);
    }

    int topDistance1 = new Random().nextInt(layoutHeight);
    int topDistance2 = new Random().nextInt(layoutHeight);
    int topDistance3 = new Random().nextInt(layoutHeight);

    while(topDistance1 == topDistance2)
    {
        topDistance2 = new Random().nextInt(layoutHeight);
    }
    while(topDistance1 == topDistance3)
    {
        topDistance3 = new Random().nextInt(layoutHeight);
    }
    while(topDistance2 == topDistance3)
    {
        topDistance3 = new Random().nextInt(layoutHeight);
    }

    params1.setMargins(leftDistance1, topDistance1, 0, 0);
    params2.setMargins(leftDistance2, topDistance2, 0, 0);
    params3.setMargins(leftDistance3, topDistance3, 0, 0);

    tv1.setLayoutParams(params1);
    tv2.setLayoutParams(params2);
    tv3.setLayoutParams(params3);

但是,有时一个文本视图可能与其他文本视图重叠并阻止用户触摸其下的文本视图。正如您从代码中看到的那样,我尝试使用while循环,但它不起作用。 (另外,我尝试使用if块,但它也没有用。)如何防止这种重叠?

以下是XML布局:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:id="@+id/layout"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity">

<TextView android:text=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/tvw1" />

<TextView android:text=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvw1"
    android:id="@+id/tvw2" />

<TextView android:text=""
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/tvw2"
    android:id="@+id/tvw3" />

0 个答案:

没有答案