I used this to set the margin programmatically, but it does not work, the margins are not applied. In the constructor:
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);
}
android:layout_marginTopSpecifies extra space on the top side of this view. This space is outside this view's bounds. Margin values should be positive. May be a dimension value, which is a floating point number appended with a unit such as " 14.5sp ".
margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.
LayoutParams are used by views to tell their parents how they want to be laid out. The base LayoutParams class just describes how big the view wants to be for both width and height.
Deducing from your comments, you're setting your params when your View
does not have LayoutParams
yet, and they are being overwritten when you attach your View
to the layout. What I would advice you to do is to move the setting of your LayoutParams
to the onAttachedToWindow
method. Then you will be able to obtain LayoutParams
with getLayoutParams()
and modify them.
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();
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With