Add images at random positions inside relative layout at runtime
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:
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>
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); // ... } }
source to share