如何在另一个类中为视图设置边距?

时间:2011-12-15 15:54:11

标签: android android-layout constructor

我做一个构造函数并以编程方式设置一些视图并添加一些规则。所以当我调用constructer时,我会看到默认视图。

现在我想达到一些观点并改变设定的保证金。这是基本的,我知道,但我非常适合我。

有人可以帮忙吗?

我的建设者的一部分:

 _photoImgVw = new ImageView(getContext());
    _photoImgVw.setImageResource(R.drawable.pic);
    _photoImgVw.setAdjustViewBounds(true);
    _photoImgVw.setMaxWidth(100);
    _photoImgVw.setId(2);


     lp2=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        lp2.setMargins(0,0,0,0);
        addView(_photoImgVw,lp2);


        LayoutParams lp3=new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
        lp3.addRule(RelativeLayout.RIGHT_OF,_photoImgVw.getId());
        lp3.setMargins(0,0,0,0);
        addView(_nameTxt,lp3);

调用活动进行更改:

 facebookPersonView.lp2.setMargins(10,300,100,20);

1 个答案:

答案 0 :(得分:0)

确保布局参数lp2是类RelativeLayout.LayoutParams的实例,而不是MarginLayoutParams,或者名为LayoutParams 的任何其他子类(那里)有很多,请参阅top of the documentation

如果params是后者的实例,它们将不包含RelativeLayout的任何规则。这意味着父布局不知道在哪里放置视图¹,因此无法理解边距。

最好以这样的方式明确声明:

RelativeLayout.LayoutParams lp2 
                    = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
                                                      LayoutParams.WRAP_CONTENT);
lp2.setMargins(0,0,0,0);
addView(_photoImgVw,lp2);

¹它仍会在左上角显示,但它是一种未定义的状态。

相关问题