2017-04-12 48 views
0

我在一个循环中dynamiclly创建多个ImageViews。 每个ImageView都有不同的位置和不同的图像。Android在一个循环中创建多个ImageViews ...奇怪的行为

最后我将它们添加到FrameLayout。

FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(container.getWidth()/3, container.getHeight()/3); 
    ImageView imageView; 
    for(int i=0; i<cloths.size(); i++) { 
     imageView = new ImageView(getActivity(), null); 
     imageView.setAdjustViewBounds(true); 
     Glide.with(getActivity()).load(cloths.get(i).getImage()).into(imageView); 

     imageView.setOnTouchListener(touchListener); 

     params.leftMargin = (int) cloths.get(i).getxPos(container.getWidth()); 
     params.topMargin = (int) cloths.get(i).getyPos(container.getHeight()); 
     params.rightMargin = 0; 
     params.bottomMargin = 0; 

     imageView.setScaleY(cloths.get(i).getScale()); 
     imageView.setScaleX(cloths.get(i).getScale()); 

     container.addView(imageView, params); 

    } 

而是正确定位的所有imageviews的,他们都在上一次的ImageView的位置铺设在彼此顶部。

enter image description here

任何想法如何解决呢? 我在做什么错?

+1

您对每个ImageView使用相同的'params'只具有不同的页边距。你为什么使用FrameLayout? FrameLayout可以存储9个位置的视图。改变利润率是不正确的方式来改变观点的立场。 –

+0

我使用FrameLayout,因为ImageViews是拖放式的! 将图像视图添加到容器时,边距只是开始边距! – Chrissss

+0

但是,你给我的解决方案... 每个循环运行创建新的参数是解决方案! – Chrissss

回答

0

假设你知道所需的位置和大小(getyPos()建议你这样做),你可以尝试聚合所有的大小,以便图像将相互重叠。如果您不知道尺寸,可以使用Glide帮助您找到它们(或者仅在图像到达后测量视图)。

public void putImages(FrameLayout container){ 
    FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(container.getWidth()/3, container.getHeight()/3); 

    int topMargin = 0; 
    for(int i=0; i<cloths.size(); i++) { 
     ImageView imageView = new ImageView(getActivity(), null); 
     imageView.setAdjustViewBounds(true); 
     Glide.with(getActivity()).load(cloths.get(i).getImage()).into(imageView); 

     imageView.setOnTouchListener(touchListener); 

     params.leftMargin = (int) cloths.get(i).getxPos(container.getWidth()); 
     params.topMargin = topMargin; 
     params.rightMargin = 0; 
     params.bottomMargin = 0; 

     topMargin += (int) cloths.get(i).getyPos(container.getHeight()); 

     imageView.setScaleY(cloths.get(i).getScale()); 
     imageView.setScaleX(cloths.get(i).getScale()); 

     container.addView(imageView, params); 
    } 
}