4

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>
2
  • probably use a recycler view, view pager ? Commented Nov 7, 2017 at 17:29
  • @zamsler did you solve your issue? I have the same problem Commented Dec 6, 2018 at 12:46

1 Answer 1

2

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.