Reputation: 307
I am trying to add multiple ImageViews to a LinearLayout. The LinearLayout is defined in the xml but I am trying to create the ImageViews with code. So far my code just makes one image in the middle even though I am trying to add the the view multiple times. Here is my main method:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout lay = (LinearLayout)findViewById(R.id.layout);
ImageView[] views = new ImageView[10];
for (int i=0;i<10;i++){
views[i] = new ImageView(this);
views[i].setImageResource(R.drawable.redeight);
lay.addView(views[i]);
}
}
}
Here is the xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
Upvotes: 4
Views: 1459
Reputation: 3869
Try this in you for loop
ImageView iv = new ImageView(this);
ViewGroup.LayoutParams params = iv.getLayoutParams();
params.height = ViewGroup.LayoutParams.WRAP_CONTENT; // Or a custom size
params.width = ViewGroup.LayoutParams.WRAP_CONTENT; // Or a custom size
iv.setLayoutParams(params);
iv.setImageResource(R.drawable.redeight);
views[i] = iv;
lay.addView(iv);
Upvotes: 2