Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: ViewGroup.MarginLayoutParams not working

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);
}
like image 610
nomnom Avatar asked Sep 25 '22 23:09

nomnom


People also ask

What is Android layout_ margintop?

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 ".

How do I set margins to recyclerView programmatically?

margin); int marginTopPx = (int) (marginTopDp * getResources(). getDisplayMetrics(). density + 0.5f); layoutParams. setMargins(0, marginTopPx, 0, 0); recyclerView.

What is LayoutParams in Android?

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.


1 Answers

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();
    }
}
like image 87
Bartek Lipinski Avatar answered Oct 11 '22 14:10

Bartek Lipinski