Android:ViewGroup.MarginLayoutParams不起作用

时间:2015-12-14 11:36:19

标签: android android-layoutparams

我用它来以编程方式设置边距,但它不起作用,边距不会应用。在构造函数中:

public TimeWindow(Context context, int pixels, int left, int top){
    super(context);
    ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(pixels, pixels);
    params.setMargins(left, top, 0, 0);
    this.setLayoutParams(params);
}

2 个答案:

答案 0 :(得分:3)

从您的评论中推断出,当您View还没有LayoutParams时,您正在设置参数,并且当您将View附加到版面时,它们会被覆盖。我建议你做的是将LayoutParams的设置移到onAttachedToWindow方法。然后,您将能够LayoutParams获取getLayoutParams()并修改它们。

private final int mPixelSize;
private final int mLeftMargin;
private final int mTopMargin;

public TimeWindow(Context context, int pixels, int left, int top){
    super(context);
    mPixelSize = pixels;
    mLeftMargin = left;
    mTopMargin = top;
}

@Override
protected void onAttachedToWindow() {
    super.onAttachedToWindow();
    if (getLayoutParams() instanceof MarginLayoutParams){ 
        //if getLayoutParams() returns null, the if condition will be false
        MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
        layoutParams.width = mPixelSize;
        layoutParams.height = mPixelSize;
        layoutParams.setMargins(mLeftMargin, mTopMargin, 0, 0);
        requestLayout();
    }
}

答案 1 :(得分:0)

将MarginLayoutParams替换为此LayoutParams:

 LayoutParams params= new LinearLayout.LayoutParams( pixels, pixels);
params.setMargins(left, top, 0, 0);
this.setLayoutParams(params);

您必须将LinearLayout.LayoutParams替换为您正在处理的布局。希望它能起作用