我用HorizontalScrollView装载个数不定的自定义ViewGroup,因为从服务器拉取数据,再呈现,但是尺寸有问题,而且两个子控件只显示了一个。我贴一下我的代码 麻烦大神帮帮忙了。
想要的效果是 这个的
上面一个ImageView,下面一个TextView
自定义的ViewGroup
public class FFTagImgView extends ViewGroup {
private Context context;
//图片
private ImageView imageView;
//标签
private TextView tagLabel;
//标志FFTAGIMGVIEW
private int tagImg;
public FFTagImgView(Context context) {
super(context);
this.context = context;
initView();
}
public static FFTagImgView newInstance(Context context,int tag){
FFTagImgView imgView = new FFTagImgView(context);
imgView.tagImg = tag;
return imgView;
}
public FFTagImgView(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
private void initView(){
this.setBackgroundColor(context.getResources().getColor(R.color.white));
this.imageView = new ImageView(context);
LinearLayout.LayoutParams lp1 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 60);
imageView.setLayoutParams(lp1);
addView(imageView);
this.tagLabel = new TextView(context);
LinearLayout.LayoutParams lp2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,20);
tagLabel.setLayoutParams(lp2);
addView(tagLabel);
}
@Override
//布局子控件,left top right bottom 当前ViewGroup相对于其父控件的坐标位置
//changed 该参数指出当前ViewGroup的尺寸或者位置是否发生了改变
protected void onLayout(boolean changed, int l, int t, int r, int b) {
//当前ViewGroup的总宽度
int mViewGroupWidth = getMeasuredWidth();
int mPainterPosX = l; //当前绘图光标横坐标位置
int mPainterPosY = t; //当前绘图光标纵坐标位置
int childCount = getChildCount();
System.out.println("子控件的个数:"+childCount);
for (int i = 0;i<childCount;i++){
View childView = getChildAt(i);
//得到子控件的宽高
int width = childView.getMeasuredWidth();
int height = childView.getMeasuredHeight();
if (i == 0){
childView.layout(0,0,mViewGroupWidth,60);
}else if(i == 1){
childView.layout(0,60,mViewGroupWidth,20);
}
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
setMeasuredDimension(70,80);
}
public ImageView getImageView() {
return imageView;
}
public void setImageView(ImageView imageView) {
this.imageView = imageView;
}
public TextView getTagLabel() {
return tagLabel;
}
public void setTagLabel(TextView tagLabel) {
this.tagLabel = tagLabel;
}
public int getTagImg() {
return tagImg;
}
public void setTagImg(int tagImg) {
this.tagImg = tagImg;
}
}
这段代码是在Activity中的使用代码:
我的效果这样。。。正常的应该填满我截图的区域
首先setMeasuredDimension(70,80);你这里都定死了宽高了,而且你第二个子view的的bottom坐标写错了,跟第一个imageview重合了应该改为childView.layout(0,60,mViewGroupWidth,80);