首页 > 解决方案 > 如何将textview放置在布局的随机位置的相对布局中?

问题描述

我正面临将文本视图random position动态放置在相对布局中的问题。textview 的总数可以是 1、3、4 ...或 30。它取决于数组列表。

我想放text view randomly in relative layout。请指导我实现它。

标签: javaandroiddesign-patterns

解决方案


尝试这个 :

   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>

推荐阅读