Search code examples
androidandroid-layoutandroid-viewandroid-inflate

How to inflate multiple instances of a layout with the same id inside an inflated layout


I have a LinearLayout with many nested LinearLayouts and TextViewss

My main activity inflates the main LinearLayout,

Then I load data from a server and based on the data received, I add multiple Layouts in a place holder (LinearLayout)

This is simple a news page where I load Images associated with the news and place it inside an initially empty LinearLayout.

Each Image has the following info: Title(TextView), Date(TextView), Image(ImageView) so what I actually do is the following:

*Please notice that this is only the essential coded in the question I elemenated all the try -> catch ... if/else ....etc

public void addImages(JSONArray images){
      ViewGroup vg = (ViewGroup) findViewById(R.id.imagesPlaceHolder);


      // loop on images
      for(int i =0;i<images.length;i++){

          View v = getLayoutInflater().inflate(R.layout.image_preview,vg);
          // then 
          I think that here is the problem 
          ImageView imv = (ImageView) v.findViewById(R.id.imagePreview);
          TextView dt = (TextView) v.findViewById(R.id.dateHolder);
          TextView ttl = (TextView) v.findViewById(R.id.title);
          // then 
          dt.setText("blablabla");
          ttl.setText("another blablabla");
          // I think the problem is here too, since it's referring to a single image
          imv.setTag( images.getJSONObject(i).getString("image_path").toString() );
          // then Image Loader From Server or Cache to the Image View

      }
}

The code above works good for a single image

But for multiple images the Image Loader doesn't work I guess it's because all ImageViews (Inflated multiple times) have the same ID


Solution

  • Is there a reason why the ImageView in the layout XML needs to have an ID? Could you erase the android:id attributes from the image_preview.xml layout and then simply iterate through the children of the inflated LinearLayout? For example:

    ViewGroup v = (ViewGroup)getLayoutInflater().inflate(R.layout.image_preview,vg);
    ImageView imv = (ImageView) v.getChildAt(0);    
    TextView dt = (TextView) v.getChildAt(1);
    TextView ttl = (TextView) v.getChildAt(2);