以编程方式Android动态添加图像按钮

时间:2012-04-13 11:14:58

标签: 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;
}

1 个答案:

答案 0 :(得分: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;



}