以编程方式放置两个ImageView

时间:2012-12-25 17:19:36

标签: android android-layout

我需要在布局中放置多个新的ImageView。问题是,一个人完全位于同一个位置。虽然我改变了位置,但它只涉及第一个。他们都是80,80。

RelativeLayout.LayoutParams lp1 = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);

    addpPicD(lp1,80,80);
    addpPicD(lp1,100,100);
}

private void addpPicD(LayoutParams lp, int Lan, int Lon) 
{

        lp.setMargins(Lan, Lon, 0, 0);
        ImageView imageView = new ImageView(this);  
        imageView.setImageResource(R.drawable.dot_bl);  
        imageView.setLayoutParams(lp);
        rel.addView(imageView);

}

2 个答案:

答案 0 :(得分:3)

RelativeLayout有自己的Layout Parameters。要并排或垂直放置子视图,您需要提供规则。对添加的每个视图的布局参数使用addRule()

传递RelativeLayout.BELOWRelativeLayout.RIGHT_OF等值以及您要与之对齐的id视图。

答案 1 :(得分:1)

您的问题是您在第一次创建布局时设置了layoutparams,然后它们不会像您认为的那样重新创建。

简单的解决方案。将其更改为下面的代码,该代码由我测试:

RelativeLayout.LayoutParams lp1 = null;

addpPicD(lp1,80,80);
addpPicD(lp1,100,100);
}

private void addpPicD(LayoutParams lp, int Lan, int Lon) 
{
    lp = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.setMargins(Lan, Lon, 0, 0);
    ImageView imageView = new ImageView(this);  
    imageView.setImageResource(R.drawable.dot_bl);  
    imageView.setLayoutParams(lp);
    rel.addView(imageView);

}