2012-04-13 37 views
1

我正在获取字符串数组的动态长度,并且我想要在图像按钮中显示图像,并且也在水平视图中添加了按钮,但它显示在垂直布局中。请帮助。这是我的代码:以编程方式动态添加imagebutton android

 for (int i =0;i<adapt_objmenu.image_array.length;i++){ 
     ImageButton b1 = new ImageButton(myrefmenu); 
      b1.setId(100 + i); 

      // b1.setText(adapt_objmenu.city_name_array[i]); 
      RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
      if (i > 0) { 
       lp.addRule(RelativeLayout.BELOW, b1.getId() - 1); 
      } 
      b1.setLayoutParams(lp); 
      relative.addView(b1); 

    //relate.addView(b1, i, new RelativeLayout.LayoutParams(width,height)); 

    //height = height+80; 



    } 
+0

如果我正确理解你的问题,你会意识到你正在设置RelativeLayout.BELOW,而RelativeLayout.RIGHT_OF会更有意义吗? – 2012-04-13 11:18:24

+0

好吧,我知道了,但如何在imagebutton上设置图像,这是主要问题 – Ved 2012-04-13 11:21:52

+0

您的意思是您想要在添加到'ImageButton'的RelativeLayout后设置图像。 – Herry 2012-04-13 11:23:55

回答

2

在第三行中使用此设置ImageButton的图像。

for (int i =0;i<adapt_objmenu.image_array.length;i++){ 
    ImageButton b1 = new ImageButton(myrefmenu); 
     b1.setId(100 + i); 
     b1.setImageResource(R.drawable.imagename); 
     // b1.setText(adapt_objmenu.city_name_array[i]); 
     RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT); 
     if (i > 0) { 
      lp.addRule(RelativeLayout.RIGHT_OF, b1.getId() - 1); 
     } 
     b1.setLayoutParams(lp); 
     relative.addView(b1); 

//relate.addView(b1, i, new RelativeLayout.LayoutParams(width,height)); 

//height = height+80; 



} 
+0

实际上,我想设置一个静态图像作为imagebutton的图像,因为我想将其显示为分页控件,就像顶部的白色圆点一样,以显示数组的长度。 – Ved 2012-04-13 11:29:28

+0

你的图片在Drawable文件夹中或在其他地方。如果在Drawable文件夹中,那么你可以使用'mImageButton.setImageResource(R.drawable.ic_launcher);' – Herry 2012-04-13 11:32:14

+0

然后,你应该准备图像资源Id的数组,并将其用于适用于你的循环。 – Herry 2012-04-13 11:33:55

相关问题