5

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

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);
}
4

2 回答 2

4

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

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();
    }
}
于 2015-12-14T13:56:07.587 回答
0

用这个 LayoutParams 替换 MarginLayoutParams 为:

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

您必须将 LinearLayout.LayoutParams 替换为您正在处理的布局。希望它会奏效

于 2015-12-14T11:49:33.100 回答