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(R.id.TableView);
        for(int i = 0; i <= n; i++){
           ImageView image = new ImageView(mContext);
           image.setImageResource(R.drawable.bg_circle);
           RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
           lp.setMargins(100,100,0,0);
           lp.height = 100;
           lp.width = 100;
           image.setLayoutParams(lp);
           layout.addView(image);
        }

Where is the mistake?

Answer

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 .