簡體   English   中英

如何在相對布局中隨機放置 textview 布局的 position?

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

我正面臨將 textview 以相對布局動態放置在random position上的問題。 textview 的總數可以是 1、3、4...或 30。這取決於數組列表。

我想text view randomly in relative layout 請指導我實現它。

嘗試這個:

   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);

在你的 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>

我建議你下一個方法:

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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM