android - 在运行时在相对布局内的随机位置添加图像

标签 android android-relativelayout

请告诉我如何在相关布局中添加图像或按钮等 View 。但是在随机位置上,图像的最大数量可以是 10。

请帮帮我。我附上了我想要最终输出的 View 。

enter image description here

问候 阿米特夏尔马

最佳答案

在这种情况下,您应该考虑 AbsoluteLayout ,这会更有意义。由于这种方式,您可以为每个 child 随机生成 xy 位置。

网上有很多例子,here是通过谷歌搜索找到的第一个。要点是这样的:

在屏幕上绘制这样的东西:

AbsoluteLayout

您可以在 Activity xml 文件中声明这样的 AbsoluteLayout:

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent">
   
<!--  Declare your shapes --> 

</AbsoluteLayout>

然后在您的 ActivityFragment 中,您将在随机位置添加您的 Shape 对象,例如:

public class MainActivity extends Activity {
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  // ...
  // Establish the working area
  DisplayMetrics displayMetrics = new DisplayMetrics();
  getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
  int widthArea = displayMetrics.widthPixels;
  int heightArea = displayMetrics.heightPixels;
  //Init the random generator
  Random r = new Random();
  // Then for each Shape  
  // ...
  AbsoluteLayout.LayoutParams pos = 
   (AbsoluteLayout.LayoutParams)shape.getLayoutParams();
  pos.x =  r.nextInt(widthArea);
  pos.y =  r.nextInt(heightArea);
  shape.setLayoutParams(pos);
  // ...
 }  
}

关于android - 在运行时在相对布局内的随机位置添加图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45417338/

相关文章:

android - RelativeLayout 可滚动

Android Button 未填满 RelativeLayout 中的全部空间

Android:为RelativeLayout设置背景图片?

android - 如何处理 :java. util.concurrent.TimeoutException : android. os.BinderProxy.finalize() 在 10 秒错误后超时?

Android - CSS 垂直居中不起作用

java - 使用自定义 View 数组的 NullPointerException

java - Android:Java:TextView 不会改变颜色

android - 如何从 Android Studio Bumblebee 隐藏缩放 Controller ?

来自另一个 View 的Android RelativeLayout alignCenter

android - RelativeLayout 设计问题 : ScrollView between a RelativeLayout and a Button