Android布局中动态添加ImageView

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



2.代码:

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

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

3.设置图片间距

        int imageMargin = mContext.getResources().getDimensionPixelSize(R.dimen.dp_2);
        int spacingInPixels = mContext.getResources().getDimensionPixelSize(R.dimen.dp_20);
                //新创建的ImageView
                ImageView imageView = new ImageView(mContext);
                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(spacingInPixels,spacingInPixels);
               lp.setMargins(imageMargin, 0, imageMargin, 0);
                imageView.setLayoutParams(lp);               

你可能感兴趣的:(Android布局中动态添加ImageView)