【问题标题】:How can i set margin to a view in another class?如何将边距设置为另一个类中的视图?
【发布时间】:2011-12-16 00:39:14
【问题描述】:

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

现在我想达到这个视图的一部分并更改设置边距。我知道这是基本的,但我不适合我。

有人可以帮忙吗?

我的构造函数的一部分:

 _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);

【问题讨论】:

  • 你能提供更多细节吗?在这种情况下,外部布局是什么?例如。如果它是 FrameLayout,则必须设置正确的重力以使边距起作用。我在this answer中解释了这一点。
  • 我们需要更多的代码,你如何实例化 lp2?
  • @alexsc 我的构造函数扩展了RelativeLayout。你在问这个吗?
  • @DuyguK 是的,编辑后很清楚。谢谢。
  • @Blundell 我创建了我的构造函数并命名为 facebookPersonView。我想达到 lp 的利润。

标签: android android-layout constructor


【解决方案1】:

确保布局参数lp2 是类RelativeLayout.LayoutParams 的实例,而不是MarginLayoutParams,或者它的任何其他名为LayoutParams 的子类(有很多,参见@ 987654321@).

如果参数是后者的实例,它们将不包含任何相对布局的规则。这意味着父布局不知道在哪里放置视图¹,因此无法从边距中获得任何意义。

最好以如下方式明确声明:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-09
    • 1970-01-01
    相关资源
    最近更新 更多