RelativeLayout.LayoutParams.WRAP_CONTENT使ImageView循环变小

时间:2015-07-01 07:27:47

标签: android android-layout

我在运行时将ImageView添加到布局中,但每次循环后ImageView都会变小。这是我的代码:

    layout = (RelativeLayout)findViewById(R.id.layout_main);
    width = getWindowManager().getDefaultDisplay().getWidth();
    height = getWindowManager().getDefaultDisplay().getHeight(
    for(int i=0; i< fruit.size();i++) {
        int id = getApplicationContext().getResources().getIdentifier(fruit.get(i).file, "drawable",
                getApplicationContext().getPackageName());
        int h = random.nextInt(height);
        int w = random.nextInt(width);
        Logger.debug(TAG, "drawable/"+fruit.get(i).file+":"+id+":X="+w+":Y="+h);
        ImageView imageView =new ImageView(getApplicationContext());
        imageView.setImageResource(id);
        imageView.setScaleX(0.3f);
        imageView.setScaleY(0.3f);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,
                                                   RelativeLayout.LayoutParams.WRAP_CONTENT);

        layoutParams.setMargins(w,h,0,0);
        imageView.setLayoutParams(layoutParams);

        layout.addView(imageView);

这是我的结果: enter image description here

请帮我解释为什么以及如何修复它? 非常感谢你

更多信息: 如果我替换代码

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,                                                              RelativeLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(w,h,0,0);
imageView.setLayoutParams(layoutParams);

通过

imageView.setY(h);
imageView.setX(w);

结果将enter image description here

2 个答案:

答案 0 :(得分:1)

可能是这个创建问题

layoutParams.setMargins(w,h,0,0);

setmargin把保证金设为 setMargins(int left,int top,int right,int bottom)

答案 1 :(得分:0)

我相信它是因为Random类。你已经绑定了随机数。如果您不希望它接近零,您可以移动生成的数字。

int h = random.nextInt(height) + height;

或者,如果您提供任何种子,您可以更改种子。请参阅以下链接。

How the random numbers are calculated.