简体   繁体   中英

How to place textview in relative layout at random position of the layout?

I am facing the issue to place the textview on the random position in relative layout dynamically. The total count of textview can be 1, 3, 4...or 30. It depend on the array list.

I want to put text view randomly in relative layout . Please guide me to achive it.

try this:

   TextView textView = findViewById(R.id.textView);
    Random random = new Random();
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);

    int random_width = random.nextInt(metrics.widthPixels - 
    textView.getWidth());
    int random_height = random.nextInt(metrics.heightPixels - 
    textView.getHeight());

    if (random_width > (metrics.widthPixels - 100)) {
        random_width -= 100;
    }

    if (random_height > (metrics.heightPixels - 200)) {
        random_height -= 200;
    }
    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    layoutParams.width = metrics.widthPixels;
    layoutParams.height = metrics.heightPixels;

    layoutParams.setMargins(random_width, random_height, 0, 0);
    textView.setLayoutParams(layoutParams);


    RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
    layoutParams.width = metrics.widthPixels;
    layoutParams.height = metrics.heightPixels;


    layoutParams.setMargins(random_width, random_height, 0, 0);
    textView.setLayoutParams(layoutParams);

and in your xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/mRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"       
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HI"
        android:textColor="#ff9999" />


</RelativeLayout>

I suggest you next approach:

RelativeLayout relativeLayout = findViewById(R.id.relativeLayout);
Random random = new Random();
int num_textViews= 10;
for (int i = 0; i < num_textViews; ++i) {
    TextView textView = new TextView(this);
    textView.setX(random.nextInt(relativeLayout.getMeasuredWidth()));
    textView.setY(-random.nextInt(relativeLayout.getMeasuredHeight()));
    relativeLayout.addView(textView);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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