2013-03-13 130 views
0

我目前正在使用图像视图和文本视图以编程方式创建framelayout。由原始布局是相对布局。设置framelaylay边距及其子宽度,高度和位置

RelativeLayout layout = (RelativeLayout) findViewById(R.id.rel); 

    FrameLayout fr = new FrameLayout(this); 
    fr.setBackgroundResource(R.drawable.question_bar_icon); 
    ImageView b1 = new ImageView(this); 
    TextView b2 = new TextView(this); 
    b1.setBackgroundResource(R.drawable.mcq); 
    fr.addView(b1); 
    fr.addView(b2); 
    layout.addView(fr); 

现在我无法调整的ImageView和按钮,也可为M无法定位他们,在verticle中心和左侧定位中心和ImageView的SENCE的TextView的。 我试过布局参数,但不工作,任何帮助将不胜感激!

回答

2

尝试使用addView的重载版本,该版本需要LayoutParameter以及在每种情况下您都以编程方式添加视图,否则将使用默认布局参数将其插入ViewGroup。 (您也可以控制插入的顺序)。

例如,对于ImageView你想成为的框架布局的中心:

int width = FrameLayout.LayoutParams.WRAP_CONTENT; //or whatever you want 
int height= FrameLayout.LayoutParams.WRAP_CONTENT; //or whatever you want 

FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(width, height, Gravity.CENTER); 

fr.addView(b1,lp); 

执行相同的另一种观点认为,和最重要的,做同样的,使用RelativeLayout.LayoutParams插入框架元素本身放入您的RelativeLayout

+0

非常感谢,它运行良好,最后一个查询,如果我必须设置边距,重力给出了位置,但是说10dp的顶边? – bharath 2013-03-13 10:30:08

+0

用任何你想要的值调用'lp.setMargins(left,top,right,bottom)'。 – 2013-03-13 10:48:29

+0

感谢Itai Hanski,工作得很好,但是当我将它添加到一个循环中时,它的重叠并只给出最后一个视图,比如想要4个这样的结构在另一个之下,是否有解决方法?由于它的相对布局不能使用设置的方向,并且设置topmargin不起作用! – bharath 2013-03-13 11:04:07