2

I trying to add image into LinearLayout (linearForImage) dynamically, but it doesn't work.

val image = ImageView(activity)
        image.setLayoutParams(LinearLayout.LayoutParams(80, 60))

        for (i in 1..5){
            linearForImage.removeView(image)
            image.setImageResource(R.drawable.ic_add)
            linearForImage.addView(image)
        }

I expect I will get 4 or 5 images in the LinearLayout, but there are no image is set.

John Joe
  • 12,412
  • 16
  • 70
  • 135

4 Answers4

1

You can modify the layout , as follows ...

Example : ( In Java )

LinearLayout linearForImage = (LinearLayout)findViewById(R.id.imageLayout);
  for(int i=1;i<6;i++)
    {
      ImageView image = new ImageView(this);
      image.setLayoutParams(new android.view.ViewGroup.LayoutParams(80,60));
      image.setMaxHeight(20);
      image.setMaxWidth(20);

      // Adds the view to the layout
       linearForImage.addView(image);
}
Farid Haq
  • 3,728
  • 1
  • 21
  • 15
1

set in view of image

ivImage.setImageResource(your drawable image)
0

Please try below code, it is working for me.

for (i in 1..5){
   val imageView = ImageView(this)
   imageView.layoutParams = LinearLayout.LayoutParams(80, 60) // value is in pixels
   imageView.setImageResource(R.mipmap.ic_launcher)
   linearForImage.addView(imageView)
}

Here is the xml file.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">



    <LinearLayout
        android:id="@+id/linearForImage"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></LinearLayout>


</RelativeLayout>

enter image description here

Chirag
  • 56,621
  • 29
  • 151
  • 198
0

set In Image view imageView.setImageResource(R.drawable.image)

Sanjib Suna
  • 284
  • 12
  • 18