Add images at random positions inside relative layout at runtime

Please let me know how I can add views like images or buttons to a relative layout. But in a random position, the maximum number of images can be 10.

Please help me. I am attaching the view as I want the final output.

enter image description here

Amit Sharma's relationship

+3


source to share


1 answer


In this case, you should consider AbsoluteLayout , it will make more sense. So you can randomly generate both x

and and y

for each child.

There are many examples on the net, here is the first one found by a google search. The bottom line is:

To draw something like this on the screen:

AbsoluteLayout

You can have AbsoluteLayout

, declared this way in your file xml

:



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

</AbsoluteLayout>
      

Run codeHide result


And then in yours Activity

or Fragment

you add your objects Shape

at random positions with something like:

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

Run codeHide result


+2


source







All Articles