Android布局中动态添加ImageView

时间:2025-02-08 08:39:12

需求:界面有时候显示图片的数量未知,需要在代码中动态添加图片。
方法步骤:
1.布局:

<LinearLayout 
    android:
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" 
    android:orientation="horizontal"
    android:layout_centerHorizontal="true">
</LinearLayout>

2.代码:

LinearLayout llGroup = (LinearLayout) findViewById(.ll_group);

//size:代码中获取到的图片数量
private void addGroupImage(int size){
    ();  //clear linearlayout
    for (int i = 0; i < size; i++) {
        ImageView imageView = new ImageView(this);
        (new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));  //设置图片宽高
        (.ic_launcher); //图片资源
        (imageView); //动态添加图片
    }
}

3.设置图片间距

        int imageMargin = ().getDimensionPixelSize(.dp_2);
        int spacingInPixels = ().getDimensionPixelSize(.dp_20);
                //新创建的ImageView
                ImageView imageView = new ImageView(mContext);
                 lp = new (spacingInPixels,spacingInPixels);
               (imageMargin, 0, imageMargin, 0);
                (lp);