2012-05-08 43 views
1

我以编程方式添加ImageView没有成功。有没有简单的方法来将ImageView以编程方式添加到Activity中?ImageView - 如何充气或以编程方式添加?

THX

编辑:

我已经试过这一点,它不工作。

   for(Bitmap b: photoField){ 
       try{ 
        Log.d("BIT", "Bitmapa "+b); 
        if(b!=null){ 
         ImageView imv=new ImageView(PoiDisplay.this); 
         imv.setImageBitmap(b); 
        } 
       }catch (NullPointerException e) { 
        e.printStackTrace(); 
       } 
      } 
+0

使用的LinearLayout。 检查[this] [1]答案。 [1]:http://stackoverflow.com/questions/4616445/align-imageview-in-linearlayout-by-code – gutiory

+1

现在,你必须在你的布局添加此ImageView的。获取活动根视图,并在其中添加这些图像视图。使用addView()方法。 – user370305

+1

假设您的布局的主要rootview是LinearLayout,然后使用findViewById()获取它,并在此for循环中添加这些图像在该LinearLayout中。 – user370305

回答

4

得到其中U要放置图像 然后

Relative or Linear or any other layout.. 

RelativeLayout urLayoutId=(RelativeLayout)finViewById(R.id.RelativeLayoutIdInXml); 

    for(Bitmap bitmap: photoField){ 
        try{ 

         if(bitmap!=null){ 
          ImageView img=new ImageView(PoiDisplay.this); 
          img.setImageBitmap(bitmap); 
          urLayoutId.addView(img); 
         } 
        }catch (NullPointerException e) { 
         e.printStackTrace(); 
        } 
      } 
+0

谢谢,你也知道,如何添加到View中“空行”?我正在动态地添加图像,这使得它们彼此躺在一起。有没有办法解决这个问题? – Waypoint

+1

@Waypoint - 使用LInearLayout而不是RelativeLayout并给出方向:vetical。 – user370305

+0

@ user370305 - 这很好,但我需要使用相对布局。我逐个添加图像,但似乎他们有固定的间距。有可能以某种方式改变它吗? ImageView.setPadding不起作用 – Waypoint

1

你只创造它不加它的布局ID。在布局上添加视图。首先创建或获取布局。

的LinearLayout LP =(的LinearLayout)findViewByid(R.id.linear_layout_name)

  for(Bitmap b: photoField){ 
      try{ 
       Log.d("BIT", "Bitmapa "+b); 
       if(b!=null){ 
        ImageView imv=new ImageView(PoiDisplay.this); 
        imv.setImageBitmap(b); 
        lp.addview(imv) 
       } 
      }catch (NullPointerException e) { 
       e.printStackTrace(); 
      } 
2

使用此代码

ImageView i=new ImageView(this); 
i.setImageResource(R.drawable.ic_launcher); 
相关问题