如何在膨胀的布局中使用相同的ID来扩充布局的多个实例

She*_*bic 24 android android-layout android-inflate android-view

我有一个LinearLayout,有很多嵌套的LinearLayouts和TextViewss

我的主要活动是膨胀主要的LinearLayout,

然后我从服务器加载数据,并根据收到的数据,我在占位符(LinearLayout)中添加多个布局

这是一个简单的新闻页面,我加载与新闻相关联的图像并将其放在最初为空的LinearLayout中.

每个图像都有以下信息:标题(TextView),日期(TextView),图像(ImageView)所以我实际做的是以下内容:

*请注意,这只是在我提出的所有尝试的问题中必不可少的代码 - > catch ... if/else ....等

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

      }
}
Run Code Online (Sandbox Code Playgroud)

上面的代码适用于单个图像

但对于多个图像,图像加载器不起作用我想这是因为所有ImageViews(多次充气)具有相同的ID

Syl*_*inL 33

当您提供要用作父级的ViewGroup时,返回的视图inflate()是此父级(vg在您的情况下)而不是新创建的视图.因此,v分向ViewGroup中vg,而不是向新创建的视图,并为所有的孩子都有相同的id,相同的子视图(imv,dt,ttl)每次都返回.

两种解决方案 第一个是id在完成下一次迭代之后改变它们的权利.因此,在下一次迭代开始时的下一次创建中,新创建的视图将具有与旧视图不同的ID,因为它们仍将使用在其中定义的旧常量R.

另一解决方案是添加参数假到呼叫膨胀(),使得新创建的视图将不会附着到的ViewGroup,然后将被充气()函数来代替的ViewGroup被返回.然后,您的其余代码将按照有人参与的方式工作,但必须在迭代结束时将它们附加到ViewGroup.

请注意,您仍需要提供ViewGroup,因为它将用于确定LayoutParams的值.


Ben*_*ton 21

我有同样的问题,根据@SylvainL的答案,这里是一个有效的解决方案:

// myContext is, e.g. the Activity.
// my_item_layout has a TextView with id='text'
// content is the parent view (e.g. your LinearLayoutView)
// false means don't add direct to the root
View inflated = LayoutInflater.from(myContext).inflate(R.layout.my_item_layout, content, false);

// Now, before we attach the view, find the TextView inside the layout.
TextView tv = (TextView) inflated.findViewById(R.id.text);
tv.setText(str);

// now add to the LinearLayoutView.
content.addView(inflated);
Run Code Online (Sandbox Code Playgroud)


use*_*495 9

布局XML中的ImageView是否需要具有ID?你可以从image_preview.xml布局中删除android:id属性,然后简单地遍历膨胀的LinearLayout的子节点吗?例如:

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);
Run Code Online (Sandbox Code Playgroud)