for loop with Image and margin

I got a problem with my for loop / with its content.
I want to have this loop in which an image is repeated n times. In addition these images should have margins at the top so they have some space between each other.

For now these images are laying on top of each other or won’t be generated as they should (Result: Drawable “bg_circle” is only displayed once).

The “userinput” will be filled from an EditText in an Alert Dialog.
Here is my code:

int n = Integer.parseInt(userInput.getText().toString());
RelativeLayout layout = findViewById(;
        for(int i = 0; i <= n; i++){
           ImageView image = new ImageView(mContext);
           RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
           lp.height = 100;
           lp.width = 100;

Where is the mistake?


Use LinearLayout with vertical orientation instead of RelativeLayout. Also, you should use a ScrollView as root element of the layout:

<ScrollView ...> <LinearLayout android:orientation="vertical" ...> ... programmatically added images... </LinearLayout> </ScrollView>

Source: stackoverflow
The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .