java - 如何将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>
推荐阅读
- typo3 - 语言页脚菜单仅显示“英语”选项 - TYPO3
- node.js - Graphql:在对象的数组字段中查找值
- ibm-odm - 异常执行在 ODM v8.10.2 上运行的规则服务(规则服务器部署在 Liberty 19.0.0.3 上)
- mysql - 存储过程比等效查询慢
- javascript - 在应用程序的全局打字稿中为 Angular 8 中的 DatePicker 设置日期最小值和最大值限制
- r - 如何在doParallel中显示进度条?
- git - 无法更改 git config 的 user.name,立即重置
- r - 如何在 R 中的一定长度的数据后停止脚本运行?
- linux - 如何将具有特定名称的文件scp到另一台服务器?
- javascript - 如何使用 react-router 创建侧边栏并设置按钮样式