简体   繁体   中英

Adding multiple Images to LinearLayout programmatically

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>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM